2010-02-17 96 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; 
}