Reputation: 182
I'm a bit new to C, and have been working on a project when I came across a weird behavior which I'd love to understand. (Probably something I'm missing).
I have the following structs:
typedef struct {
char *name;
int status;
int strength;
} Pig;
typedef struct {
char *name;
char color[10];
int injuryPower;
int penType;
} Bird;
When I allocate the pig, like this, it works normally:
Pig *pig_1 = malloc(sizeof(Pig *));
pig_1->status = 2;
pig_1->strength = 7;
pig_1->name = malloc(sizeof(char) * 11);
pig_1->name = "PigA\0";
But when I allocate the bird, in a similar manner, I have this weird behavior:
Bird *bird_1 = malloc(sizeof(Bird *));
1) bird_1->penType = 2;
2) bird_1->injuryPower = 5;
3) bird_1->name = malloc(sizeof(char) * 6);
bird_1->name = "BirdA\0";
bird_1->color[0] = 'R';
bird_1->color[1] = 'e';
bird_1->color[2] = 'd';
bird_1->color[3] = '\0';
In line (1) pen type is getting defined to 2.
In line (2) pen type is still 2.
In line (3) pen type gets changed according to the value I define in the bracets, so in this example it'll change to 35.
I am using Cygwin 64 bit as my compiler.
Could someone please explain what I am missing here, why is the value of pen type changing even though I am not altering it?
Is it due to malloc? Am I doing something incorrectly?
Thanks a lot!
Upvotes: 0
Views: 753
Reputation: 192
Pig *pig_1 = malloc(sizeof(Pig *));
...
Bird *bird_1 = malloc(sizeof(Bird *));
You're allocating the size of a pointer not the size of the structure.
Pig *pig_1 = malloc(sizeof(Pig));
...
Bird *bird_1 = malloc(sizeof(Bird));
Will reserve enough space for the whole structure.
Because you are only allocating enough memory for the first member of your structure (also a pointer), the other members are in an area of memory that could be reserved for other variables. What you are seeing is the value of another variable being changed and reflected in your structure.
Upvotes: 2