Hi I ran in to this situation. I am using malloc to give me an array of 10 pointers. When I see the test pointers in gdb, one of them(the third )points to 0x0. Sometimes the code segfaults when using apple[2]->string = “hello”. Why does malloc do this? Thanks in advance for the help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void)
{
typedef struct test
{
char *string;
int data;
} test;
test *apple[10]; // Declare an array of 10 test pointers. This line results in one of the pointers having a null value.
apple[0] = malloc(sizeof(test));
apple[0]->string = "hello";
printf("The string is %s\n",apple[0]->string);
printf("Size of apple[0]->data is %d\n",sizeof(apple[0]->data));
printf("Size of tester is %d\n",sizeof(test));
free(apple[0]);
return 0;
}
I wanted to see how the array of pointers would work. I was not intending on using all the 10 pointers. So do I need to malloc only what I need? Is it a coincidence, that the third pointer was 0x0?
Memory has only been allocated for first element in
appleso onlyapple[0]points to a validstruct test.To allocate memory for all elements of
apple:Similar loop required to
free().test.stringis achar*, so pointing to a string literal as you have done is fine (though type should beconst char*). If you wish to copy a string totest.stringthen you mustmalloc()space to copy into andfree()it later.