【问题标题】:malloc() memory corruptionmalloc() 内存损坏
【发布时间】:2015-04-06 06:16:36
【问题描述】:

我正在编写一个程序来从文件中读取任意数量的行(其中第一行是我不需要的标题),并为它们动态分配内存。

char buffer[350];
char** addresses;
char** temp;
int i = 0;
int check = 10;

addresses = malloc(sizeof(char*) * check); /* let's start with 10 potential  addresses */

if(addresses == NULL){
    printf("Unable to allocate memory.\n");
    exit(1);}

fgets(buffer, sizeof(buffer), stdin); /* call this once to get past the header line */


while(fgets(buffer, sizeof(buffer), stdin) != NULL)
{

    if(i > check) /* we need more memory */
    {
        temp = realloc(addresses,(2*check)*sizeof(char*)); /* double the memory we have */
        if(temp == NULL)
        {
            printf("Unable to re-allocate memory");
            exit(1);
        }
        else
        {
            addresses = temp;
            check *= 2;
            printf("reallocating to %d\n", check);
        }           
    }

    addresses[i] = malloc(strlen(buffer)); /* get memory for number of chars in each line */
    printf("2 %d\n", i);
    strcpy(addresses[i],buffer);
    i++;
}

当我运行它时,我得到一个内存损坏错误:

reallocating to 20
reallocating to 40
reallocating to 80
reallocating to 160
reallocating to 320
reallocating to 640
*** glibc detected *** ./a.out: malloc(): memory corruption:     0x0000000007721310 ***
======= Backtrace: =========
/lib64/libc.so.6[0x37f0a71fbe]
/lib64/libc.so.6(__libc_malloc+0x6e)[0x37f0a73dfe]
./a.out[0x400789]
/lib64/libc.so.6(__libc_start_main+0xf4)[0x37f0a1d9f4]
./a.out[0x4005d9]

这是什么原因造成的?

【问题讨论】:

    标签: c memory malloc corruption


    【解决方案1】:
    addresses[i] = malloc(strlen(buffer)); /* get memory for number of chars in each line */
    printf("2 %d\n", i);
    strcpy(addresses[i],buffer);
    

    您没有为终止 NUL 字符分配空间。

    【讨论】:

    • 要解决这个问题,请将1 添加到strlen 的结果中。或使用strdup
    • @M.M 我该如何感谢你。我刚刚看到你的答案并在我的代码中检查了 strdup() ......我已经浪费了将近一天的时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2011-06-04
    • 1970-01-01
    相关资源
    最近更新 更多