Search code examples
cmemory-managementstack-dump

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);
}

Solution

  • 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 );
    }