首页 > 解决方案 > Realloc 崩溃:cygwin_exception::open_stackdumpfile:将堆栈跟踪转储到 malloc.exe.stackdump

问题描述

我是动态内存分配的新手,我尝试编写一个简单的程序来连接 2 个字符串(一个已初始化,一个从标准输入读取),使用 realloc 作为第一个字符串。但我收到此错误:

cygwin_exception::open_stackdumpfile:将堆栈跟踪转储到 malloc.exe.stackdump

代码在 realloc 处中断,我不知道为什么,您能帮忙吗?

输入:活着的人。

预期输出:活着的最心爱的人。

我尝试用数字替换 strlen 但无济于事。

这是我的代码:

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

int main()
{
    char *str = "The most beloved";
    char str2[20];
    scanf("%[^\n]%*c", str2);
    //printf("%s %s\n", str, str2);

    str = (char *)realloc(str, strlen(str) + strlen(str2));

    strcat(str, str2);
    printf("%s\n", str);
    free(str);
}

标签: cdynamic-memory-allocationstring-concatenationreallocstring-literals

解决方案


您正在分配一个str未使用分配的指针malloc。您可以将指针传递给freerealloc仅在它们已被分配时使用malloc.

正确使用 realloc()

你可以做

str = strdup("mystring");

同样在这里你需要考虑到\0最后,所以它应该是:

str = (char *)realloc(str, strlen(str) + strlen(str2)+1);

推荐阅读