c++ - 如何纠正 C++ 中的 malloc 错误?附加字符时
问题描述
void append(char* &s, const char& ch)
{
/*
Appends the character ch to the cstring s.
That is ch is added to the end of s making sure the resulting s is a valid cstring
The parameter s is assumed to be a dynamic array
*/
int len = cstrlen(s);
int newLen = len + 1;
char *C = new char[newLen + 1];
C[len] = ch;
C[newLen] = '\0';
for (int i = 0; i < len; i++)
C[i] = s[i];
delete [] s;
s = C;
return;
}
这是我的输出窗口
Testing append function
----------------------
Appending ch='v' to s2="" gives s2="v"
Appending ch='x' to s2="v" gives s2="vx"
Appending ch='i' to s2="vx" gives s2="vxi"
Appending ch='r' to s2="vxi" gives s2="vxir"
Appending ch='i' to s2="vxir" gives s2="vxiri"
Appending ch='u' to s2="vxiri" gives s2="vxiriu"
Appending ch='u' to s2="vxiriu" gives s2="vxiriuu"
Appending ch='o' to s2="vxiriuu" gives s2="vxiriuuo"
Appending ch='s' to s2="vxiriuuo" gives s2="vxiriuuos"
Appending ch='b' to s2="vxiriuuos" gives s2="vxiriuuosb"
Appending ch='y' to s2="vxiriuuosb" gives s2="vxiriuuosby"
Appending ch='u' to s2="vxiriuuosby" gives s2="vxiriuuosbyu"
Appending ch='w' to s2="vxiriuuosbyu" gives s2="vxiriuuosbyuw"
Appending ch='j' to s2="vxiriuuosbyuw" gives s2="Assignment 3 Tester(34580,0x1000efe00)
malloc: *** error for object 0x1007040d0: pointer being freed was not allocated
Assignment 3 Tester(34580,0x1000efe00) malloc: *** set a breakpoint in malloc_error_break to debug
Assignment 3 Tester(34580,0x1000efe00) malloc: *** error for object 0x1007040d0: pointer being freed was not allocated
如您所见,代码在某些迭代中运行良好,但随后出现malloc
错误。我从来没有遇到过这样的事情,有人可以解释发生了什么或者代码错误吗?拨打电话的代码是:
//Test append function
cout << endl << "Testing append function";
cout << endl << "----------------------" << endl;
for (int i = 0; i < 20; i++)
{
ch = rand() % 26 + 97;
cout << "Appending ch='" << ch << "' to s2=\"" << s2 << "\" gives s2=\"";
append(s2, ch);
cout << s2 << "\"" << endl;
}
注意-我使用 Xcode。下面的线是红色的。我不知道这意味着什么,但也许它会给你一些线索。
-> 0x7fff202554c8 <+151>: movq 0x5fec07d9(%rip), %rax ; (void *)0x00007fff88a5aa30: __stack_chk_guard
Thread 1: signal SIGABRT
谢谢
解决方案
推荐阅读
- sql - Azure SQL - 如何从输出中删除属性文本
- sql-server - 在子查询中获取 DISTINCT 值
- linux - 受限设备上的 MPI 是 Linux 上进程间通信的好选择吗?
- jquery - 为什么我有一个 JS 错误“我是未定义的 jquery.datatables.min.js”
- go - dynamodbattribute.MarshalMap 返回空地图
- git - 从 Visual Studio 2017 获取和提取的 Git 未获得最新提交
- firefox - Firefox 没有显示 Bootstrap 的 CSS 过渡
- azure - 如何在 Azure 中查看所有用户的列表以及分配给他们的角色?
- r - 因子水平是“有序”中的重复错误
- asp.net - 无法在 ASP.NET WebGrid 中添加 HTML.BeginForm