gpt4 book ai didi

c - 动态字符串列表和 free() 导致应用程序崩溃

转载 作者:行者123 更新时间:2023-11-30 19:42:42 24 4
gpt4 key购买 nike

我编写了一个简单的 C 代码,该代码应在结构内存储字符串地址 (char*) 列表。该列表是动态的,因此每次添加新字符串时,我都会保留足够的内存来存储所有当前字符串地址以及新字符串地址。然后我释放旧缓冲区并将新缓冲区分配给该结构。问题是它在 free() 上崩溃。

我确信我可以 free() 从 calloc() 获得的确切地址,但它仍然崩溃。

这是输出:

main(3618,0x7fff7a83f300) malloc: *** error for object 0x7f9902404bd0: incorrect checksum for freed object - object was probably modified after being freed.

代码是:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct StructNODE{
char** stringlist;
int stringcount;
struct StructNODE* next;
} NODE;


void Addstring(NODE* node, const char* string)
{
int currentBufferSize = node->stringcount * sizeof(char*);

// make room for the current string list plus the new one
char** addrList = (char**) calloc( 1, currentBufferSize );
printf("malloc: %d bytes starting at 0x%X\n",currentBufferSize, addrList);

// copy all current addresses to the new list
memcpy(addrList, node->stringlist, currentBufferSize);

printf("freeing mem at 0x%X\n",node->stringlist);
free(node->stringlist);

// Append the new address to the end of the address buffer
addrList[node->stringcount] = (char*)string;

//make the node point to the new buffer
node->stringlist = addrList;

// Increment the string number counter
node->stringcount++;

}

void PrintStringlist(NODE* node)
{
int i;
for ( i=0; i < node->stringcount; i++)
{
printf("string %d: %s\n",i, node->stringlist[i]);
}
}

int main(int argc, char** argv)
{
NODE* node = (NODE*) calloc(1 , sizeof(NODE));

Addstring(node, "Lewis Skolnick");
Addstring(node, "Gilbert Lowe");
Addstring(node, "Arnold Poindexter");
Addstring(node, "Harold Wormser");
Addstring(node, "Booger");
Addstring(node, "Takashi Toshiro");
Addstring(node, "Lamar Latrelle");
Addstring(node, "Judy");

PrintStringlist(node);

return 0;
}

我忽略了什么?

最佳答案

您的缓冲区太小 - 您忘记为额外元素添加空间。第一个功能行应为:

    int currentBufferSize = (node->stringcount + 1) * sizeof(char*);

关于c - 动态字符串列表和 free() 导致应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31063569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com