ant2009
ant2009

Reputation: 22526

nested structures allocating memory

gcc c89

I am getting a stack dump on this line:

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

However, I have allocated memory, so not sure why I would be getting it. Am I missing something here?

Many thanks 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;
}

Upvotes: 3

Views: 9573

Answers (4)

Sandeep Singh
Sandeep Singh

Reputation: 5191

Here, you are not allocating any memory for the struct member 'persons'.

I have modified your code:

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

Upvotes: 0

sharptooth
sharptooth

Reputation: 170499

You need to allocate memory for persons:

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

and don't forget to free that memory later.

Upvotes: 7

Jay
Jay

Reputation: 24895

Memory is not allocated for "persons" field of struct company structure. If you allocate memory for that it should be fine.

Upvotes: 2

matekm
matekm

Reputation: 6030

You have allocated memory for company structure, but haven't for emp structure

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

after that You can access memory stored in comp->person

Upvotes: 2

Related Questions