tags:

views:

70

answers:

3

Hello,

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;
}
+2  A: 

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

matekm
+2  A: 

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

Jay
+3  A: 

You need to allocate memory for persons:

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

and don't forget to free that memory later.

sharptooth