C/Memory allocation
Expert: Zlatko - 12/20/2011
QuestionDear Hi,
I am facing segmetation fault in c program. I am suspecting below piece of code.
char **name = (char**)malloc( sizeof( char *) );
name[0] = (char*)malloc(50 * sizeof( char *));
strcpy( name[0], "GBL_COLLECTOR\0" );
Is there any issue on above code?
AnswerHello Lakshmipathy
The code you sent me would not cause a seg fault on its own, but I suspect it has some problems.
The line:
char **name = (char**)malloc( sizeof( char *) )
is creating an array of pointers, but in this case the array has only 1 element, so you can use name[0], but there is no name[1]. You should probably have something like this:
#define NAME_COUNT 10
char **name = (char**)malloc( sizeof( char *) * NAME_COUNT);
to make name an array of 10 pointers
The line :
(char*)malloc(50 * sizeof( char *));
is probably intended to allocate space for 50 characters, but actually it allocates space for 200 characters, because sizeof(char*) is 4. A char* is a pointer, and (on 32 bit systems), all pointers are 4 bytes long. Allocating more space than is needed will not cause the seg fault, but it is wasteful. If you want space for 50 characters, use this:
(char*)malloc(50 * sizeof(char));
Best regards
Zlatko