堆栈转储访问malloc char数组

ant*_*009 5 c memory-management stack-dump

gcc 4.4.3 c89

我有以下源代码.并在printf上获得堆栈转储.

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

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

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

我想这应该创建一个这样的char数组.

devices[0]
devices[1]
devices[2]
devices[4]
etc
Run Code Online (Sandbox Code Playgroud)

每个元素我都可以存储我的字符串.

非常感谢任何建议,

==增加了更正===

for(i = 0; i < 10; i++)
{
    devices[i] = malloc(strlen("smxxxx1")+1);
}
Run Code Online (Sandbox Code Playgroud)

use*_*019 5

您已为指针数组分配了内存.您需要为每个元素分配内存以存储字符串

例如

#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 );
}
Run Code Online (Sandbox Code Playgroud)