首页 > 解决方案 > 如何纠正 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

谢谢

标签: c++malloc

解决方案


推荐阅读