Drop stack using malloc char array

gcc 4.4.3 c89

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

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

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

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

I think this should create a char array similar to this.

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

And each item I can store my lines.

Thanks so much for any suggestions,

== Added correction ===

for(i = 0; i < 10; i++)
{
    devices[i] = malloc(strlen("smxxxx1")+1);
}
+5
source share
6 answers

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

eg.

#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 );
}
+5
source

devices [0] - this char *, but you have not allocated any storage for it. Do this instead:

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

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

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

In the end, you need to free the memory allocated strdup():

free(devices[0]);
+4
source

10 char. , . - device[0] = malloc(stringLen + 1); .

+3

. , :

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 */
+2

(), , .

+1

- . "smxxxx1" , , 0, .

strcpy() try:

devices[0] = "smxxxx1"

devices[0] = strdup("smxxxx1")

Edit:

32- [0] . "smxxxx1". ascii 0x73, 0x6D, 0x78, 0x78. little-endian , [0], 0x78786D73. . printf() , .

, OP ( char). char, printf() .

0
source

All Articles