我正在将整数转换为字符串并将它们添加到动态分配的数组中。问题是它导致了段错误。我不明白为什么会发生这种情况。
#include <stdio.h>
#include <stdlib.h>
int main() {
char *x = malloc(10 * sizeof(char));
x[0] = malloc(10 * sizeof(char));
sprintf(x[0],"%d",10);
for(int i = 0; i < 10;i++){
free(x[i]);
}
free(x);
return 0;
}
最佳答案
要分配一个元素为char*
的数组,指向该数组的指针应该是char**
,而不是char*
。
此外,您不得使用通过 malloc()
分配且未初始化的缓冲区中的值。这些值是不确定的,使用它们会调用未定义的行为。
#include <stdio.h>
#include <stdlib.h>
int main() {
/* correct type here (both variable and allocation size) */
char **x = malloc(10 * sizeof(char*));
x[0] = malloc(10 * sizeof(char));
sprintf(x[0],"%d",10);
/* initialize the other elements to pass to free() */
for (int i = 1; i < 10; i++) x[i] = NULL;
for(int i = 0; i < 10;i++){
free(x[i]);
}
free(x);
return 0;
}
关于c - 在动态分配的数组中使用 sprintf 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67366162/