c - 在动态分配的数组中使用 sprintf 时出现段错误

标签 c printf

我正在将整数转换为字符串并将它们添加到动态分配的数组中。问题是它导致了段错误。我不明白为什么会发生这种情况。

#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/

相关文章:

创建节点列表

c - 如何在 C 中使用动态多维数组?

c++ - DWMEnableBlurBehind 使我的界面控件半透明

c - printf 反转字符串时输出错误

c - 为什么 scanf 返回负数时不使用 printf()?

c - 使用 OpenGL 和 GLFW 操作 C 数组

C 字符数组在传递给函数后损坏

c - 解释 C 代码片段 : preprocessor + printf =?

c - 为什么这个 print 语句可以阻止 C 程序崩溃?

c - 如何允许使用 scanf 输入空格?