双重释放或内存损坏

发布于 2025-01-06 15:43:13 字数 868 浏览 2 评论 0原文

我有这样的代码

char *verboseBuf = NULL;
if(somethin){
    for(a loop){
        for(another loop){
            if(somethin else){
                if(curl execution){
                    if(fail){
                        verboseBuf = (char *) malloc(sizeof(char) * (currSize +1));
                        fread(verboseBuf, 1, currSize, verboseFd);
                        verboseBuf[currSize + 1] = '\0';
                        string verbose = verboseBuf;
                        free(verboseBuf);
                    }   
                }   
            }   
        }   
    }   
}

我使用 verboseBuf 的唯一地方是在最后的 if 循环内。但我明白了,

*** glibc detected *** ./test: double free or corruption (!prev): 0x13c13290 ***

但是如果我只在一个地方使用它,怎么能释放它两次呢?每次我使用它时,我都会释放它。 我尝试使用 addr2line 来查找之前释放它的位置,但得到的只是 ??:0

I have a code like this

char *verboseBuf = NULL;
if(somethin){
    for(a loop){
        for(another loop){
            if(somethin else){
                if(curl execution){
                    if(fail){
                        verboseBuf = (char *) malloc(sizeof(char) * (currSize +1));
                        fread(verboseBuf, 1, currSize, verboseFd);
                        verboseBuf[currSize + 1] = '\0';
                        string verbose = verboseBuf;
                        free(verboseBuf);
                    }   
                }   
            }   
        }   
    }   
}

The only place that i use the verboseBuf is inside the final if loop. but i get

*** glibc detected *** ./test: double free or corruption (!prev): 0x13c13290 ***

But how can be freeing it twice if i only use it in one place? and everytime i use it, i free it.
I tried using addr2line to find the place where it was freed previously but all got was a ??:0.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

抹茶夏天i‖ 2025-01-13 15:43:13

这一行正在向缓冲区末尾写入一个字节。

verboseBuf[currSize + 1] = '\0';

This line is writing one byte past the end of your buffer.

verboseBuf[currSize + 1] = '\0';
念﹏祤嫣 2025-01-13 15:43:13

该消息并不具体意味着您两次释放某些内容,而是意味着 glibc 检测到堆损坏,并且释放两次内容是造成这种情况的一个常见原因,但不是唯一的原因。

在这种情况下,该行

verboseBuf[currSize + 1] = '\0';

溢出了缓冲区的末尾,从而破坏了分配器在其之后存储的所有簿记数据。删除+1,它应该可以工作。

That message doesn't specifically mean that you freed something twice, it means that glibc detected heap corruption, and freeing things twice is one common cause of that, but not the only one.

In this case, the line

verboseBuf[currSize + 1] = '\0';

is overflowing the end of your buffer, corrupting whatever bookkeeping data the allocator stored after it. Remove the +1 and it should work.

慈悲佛祖 2025-01-13 15:43:13

verboseBuf[currSize + 1] = '\0'; 设为 verboseBuf[currSize] = '\0';

Make verboseBuf[currSize + 1] = '\0'; as verboseBuf[currSize] = '\0';

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文