c - 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);
}
解决方案
您正在分配一个str
未使用分配的指针malloc
。您可以将指针传递给free
或realloc
仅在它们已被分配时使用malloc
.
你可以做
str = strdup("mystring");
同样在这里你需要考虑到\0
最后,所以它应该是:
str = (char *)realloc(str, strlen(str) + strlen(str2)+1);
推荐阅读
- c++ - 我可以强制提升在 Windows 上更喜欢正斜杠吗?
- odoo - 如何从 Odoo13 中的自定义模块生成发票?
- c - 有没有办法在没有所有重复 if 语句的情况下完成以下循环?
- json - 在角度2+的连接方法中插入html标签不起作用
- python - Python-为什么即使我输入了应该可以使用的密码,它也会说密码被拒绝?
- swift - 从剪贴板快速粘贴音频文件(.mp3、.m4a 等)并保存
- java - 无法将 Mpesa Api 集成到我的 Android 应用程序中
- node.js - 如何访问使用混合类型模式的 mongoose 查询的 mongodb 数据中的每个字段值
- python - 有机会的记号
- reactjs - ReactNative & Expo:离子不渲染