c - Malloc 二维数组可能大小溢出

标签 c malloc

这是我的程序的简化版本。

#include <stdio.h>

int main(void) {

    char **words, **nwords;

    int x;
    words = malloc(sizeof *words * 1000);
    if (words) {
        for (x = 0; x < 20; x++) {
            words[x] = malloc(sizeof *words[x] * 1); 
        }   
    }   

    nwords = malloc(sizeof *nwords * 1000);
    if (nwords) {
        for (x = 0; x < 20; x++) {
            nwords[x] = malloc(sizeof(char) * 200);
            //nwords[x] = "123456789012345"; // works correctly
            nwords[x] = "1234567890123456"; // garbage
        }   
    }   

    int i;
    for (i=0; i<10;i++) {
        sprintf(words[i],"%s",nwords[i]);
    }   

    for (i=0; i<10;i++) {
        printf("\n words[%d] = %s",i,words[i]);
    }   

    return 0;
}

如果 nwords[x] 中的字符数增加超过 15,则最终 printf 开始打印奇怪的串联输出。 (参见 nwords[x] = "1234567890123456";//garbage 行)为什么会这样?我使用 malloc 给了它 200 个值得内存的字符。

最佳答案

有了这个声明

words[x] = malloc(sizeof *words[x] * 1); 

您将单个字符分配给 words[x]。然后你做

sprintf(words[i],"%s",nwords[i]);

将多个字符写入 words[i]


还有,用

nwords[x] = malloc(sizeof(char) * 200);
nwords[x] = "1234567890123456"; // garbage

你首先让 nwords[x] 指向你从堆中分配的一些内存,然后直接让它指向一个字符串文字。你可能想要任何一个

nwords[x] = malloc(sizeof(char) * 200);
strcpy(nwords[x], "1234567890123456");

nwords[x] = strdup("1234567890123456");

关于c - Malloc 二维数组可能大小溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20235412/

相关文章:

c - 将 unsigned char 移动超过 8 位

连接 2 个字符串

C编程制作乘法表(1-12)

c - 无法使用 gcc48 编译我的 C 文件

c - 如何在 ANSI C 中分配一 block 内存,然后打开它们的所有位

linux - 为什么我会收到 malloc 错误?

c++ - 帮助解决 c 错误

c - 在 C 中从文件读取大数(例如 e 和 pi)到数组

C 编程字符串、指针和分配

c - strcat 和 malloc