Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack dump accessing malloc char array

gcc 4.4.3 c89

I have the following source code. And getting a stack dump on the printf.

char **devices;
devices = malloc(10 * sizeof(char*));

strcpy(devices[0], "smxxxx1");

printf("[ %s ]\n", devices[0]); /* Stack dump trying to print */

I am thinking that this should create an char array like this.

devices[0]
devices[1]
devices[2]
devices[4]
etc

And each element I can store my strings.

Many thanks for any suggestions,

== Added correction ===

for(i = 0; i < 10; i++)
{
    devices[i] = malloc(strlen("smxxxx1")+1);
}
like image 480
ant2009 Avatar asked May 12 '10 08:05

ant2009


4 Answers

You have allocated memory for an array of pointers. You need to allocate the memory for each element to store the string

e.g.

#define NUM_ELEMENTS 10
char **devices;
devices = malloc(NUM_ELEMENTS  * sizeof(char*));

for ( int i = 0; i < NUM_ELEMENTS; i++)
{
    devices[i] = malloc( length_of string + 1 );
}
like image 191
mmmmmm Avatar answered Oct 23 '22 20:10

mmmmmm


devices[0] is a char *, but you haven't allocated any storage for it. Do this instead:

char **devices;
devices = malloc(10 * sizeof(char*));

devices[0] = strdup("smxxxx1");

printf("[ %s ]\n", devices[0]);

Eventually, you'll have to free the memory allocated by strdup():

free(devices[0]);
like image 44
Marcelo Cantos Avatar answered Oct 23 '22 19:10

Marcelo Cantos


You have allocated memory for storing 10 char pointers. To store a string at these memory location you have to allocate memory for each of them. Basically you need something like device[0] = malloc(stringLen + 1); for each pointer.

like image 31
Naveen Avatar answered Oct 23 '22 19:10

Naveen


You only have allocated an array of pointers to character-arrays. You will have to allocate memory for each string you plan to store:

char **devices;
devices = malloc(10 * sizeof(char*));

//Added this line:

devices[0] = (char*)malloc(strlen("smxxxx1")+1);
strcpy(devices[0], "smxxxx1\0");

printf("[ %s ]\n", devices[0]); /* Stack dump trying to print */
like image 40
sum1stolemyname Avatar answered Oct 23 '22 19:10

sum1stolemyname