如何修复“堆已损坏”运行时错误?

问题描述 投票:0回答:1

我正在尝试创建一个获取指针数组指针的代码。指针指向字符串,但每个指针都分配了50个字节的内存,因此我使用此函数来分配最小的内存量。但由于某种原因,realloc会引发运行时错误(堆已损坏)。有关问题根源以及如何解决问题的任何想法?

int reallocToMinSize(char** friends, int len)
{
    int i = 0;
    int reallocSuccess = 1;
    char* newFriendPtr = 0;

    for (i = 0; i < len && reallocSuccess; i++)
    {
        printf("Reallocating: %s, size: %i", friends[i], (strlen(friends[i]) + 1));
        friends[i] = (char*) realloc(friends[i], (strlen(friends[i]) + 1) * sizeof(char));
        if (friends[i] == 0)
        {
            reallocSuccess = 0;
        }
        printf("%s\n", friends[i]);
    }
    return reallocSuccess;
}
c heap-memory
1个回答
0
投票

可能的原因是

  • 你从来没有初始化friends[i]之前做realloc
  • 或者你重新分配一个释放的块
  • friends[i]未设置为NULL或malloc的结果

因为你这样做

 realloc(friends[i], (strlen(friends[i]) + 1) * sizeof(char));

以前的printf可能是有效的我怀疑你是在第三个错误的情况下,你做错了像

friends[i] = "aze";
... 
reallocToMinSize(friends, ...);

要么

char s[...];
... 
friends[i] = s;
... 
reallocToMinSize(friends, ...);

要么

char * s = malloc(...);
... 
friends[i] = s + offset; /* offset not null */
... 
reallocToMinSize(friends, ...);

要么

... 
friends[i] = strtok(...);
... 
reallocToMinSize(friends, ...);

或者可能是第二个错误案例

char * s = malloc(...); /* unique allocation */
...
for (i = ...) { ... friends[i] = s; ... } /* always the same value of s */
... 
reallocToMinSize(friends, ...);

因为malloc可以释放它的第一个参数,所以在给定索引的reallocToMinSize中,对一个为较低索引释放的块应用realloc

© www.soinside.com 2019 - 2024. All rights reserved.