2010-02-17 81 views
3

GCC C89嵌套结构分配内存

我在这条线得到一个堆栈转储:

strcpy(comp->persons->name, "Joe"); 

不过,我已经分配的内存,所以不知道为什么我会得到它。我在这里错过了什么吗?

非常感谢任何建议,

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

struct company 
{ 
    struct emp *persons; 
    char company_name[32]; 
}; 

struct emp 
{ 
    char name[32]; 
    char position[32]; 
}; 

int main(void) 
{  
    struct company *comp; 

    comp = malloc(sizeof *comp); 
    memset(comp, 0, sizeof *comp); 

    strcpy(comp->persons->name, "Joe"); 
    strcpy(comp->persons->position, "Software Engineer"); 

    printf("Company = [ %s ]\n", comp->company_name); 
    printf("Name ==== [ %s ]\n", comp->persons->name); 
    printf("Postion ==== [ %s ]\n", comp->persons->position); 

    free(comp); 

    return 0; 
} 

回答

5

您需要为persons分配内存:

comp->persons = malloc(sizeof(struct emp) * NumberOfPersonsYouExpectToHave); 

,不要忘记稍后释放内存。

2

您已经分配给公司结构的内存,但没有对EMP结构

你必须为comp->person分配内存:comp->person = (struct emp*)malloc(sizeof(emp))

后您可以访问存储在comp-> person中的内存

2

内存未分配给struc的“persons”字段公司结构。如果你为它分配内存,它应该没问题。

0

在这里,你没有为struct member'persons'分配任何内存。

我已修改了代码:

struct 
{ 
    struct emp *persons; 
    char company_name[32]; 
} company; 

struct emp 
{ 
    char name[32]; 
    char position[32]; 
}; 

int main() 
{  
    int num_persons = 1; 
    company.persons = malloc(sizeof(struct emp)*num_persons); 
    if (NULL == company.persons) 
    { 
     printf ("\nMemory Allocation Error !\n"); 
     return 1; 
    } 
    strcpy(company.persons->name, "Joe"); 
    strcpy(company.persons->position, "Software Engineer"); 
    strcpy(company.company_name, "My_Company"); 
    printf("Company = [ %s ]\n", company.company_name); 
    printf("Name ==== [ %s ]\n", company.persons->name); 
    printf("Postion ==== [ %s ]\n", company.persons->position); 

    return 0; 
}