Nested memory allocation structures

gcc c89

I get a stack dump on this line:

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

However, I allocated the memory, so I'm not sure why I get it. Did I miss something?

Thanks so much for any advice,

#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;
}
+3
source share
4 answers

You need to allocate memory for persons:

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

and don't forget to free this memory later.

+5
source

You have allocated memory for the company structure, but not for the emp structure

You must allocate memory for comp->person:comp->person = (struct emp*)malloc(sizeof(emp))

after that you can access the memory stored in comp-> person

+2
source

"" . , .

+2

- - .

:

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;  
}  
0

Source: https://habr.com/ru/post/1733135/


All Articles