堆在realloc()上已损坏
A heap has been corrupted on realloc()
我正试图编写一个通用函数来调整大小和连接字符串,但在调用realloc()时发生运行时异常,说明堆已损坏。
//two string pointer initialized with malloc()
wchar_t* stream;
wchar_t* toAdd;
stream = (WCHAR *)malloc(sizeof(wchar) );
toAdd= (WCHAR *)malloc(sizeof(wchar) );
//function declaration
int ReallocStringCat(wchar_t *, const wchar_t *);
//
int ReallocStringCat(wchar_t *dest,const wchar_t *source)
{
//below line throws a heap corrupt exception
*dest =(wchar_t) realloc(dest, wcslen(dest) + wcslen(source) + 1);
return wcscat_s(stream,wcslen(dest) + wcslen(source) + 1, source);
}
我敢肯定我在使用指针和地址时哪里出错了,但我不知道。
也有任何内置功能,如可变类可用在Visual Studio 2012 c++原生Win32 c++应用程序没有任何CLR/MFC/ATL库?
您需要在realloc中提供字节大小而不是wchar_t的数量:
dest =(wchar_t *) realloc(dest, (wcslen(dest) + wcslen(source) + 1)*sizeof(wchar_t ));
*dest =(wchar_t) realloc(dest, wcslen(dest) + wcslen(source) + 1);
应该dest =(wchar_t*) realloc(dest, sizeof(wchar_t ) * ( wcslen(dest) + wcslen(source) + 1) );
您还创建了内存泄漏,因为dest
正在更改,而不是由函数返回。
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么C中的通用链表中存储的数据已损坏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 变量周围的堆栈'...'已损坏
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- 两个垫子的 OpenCV 数据是相同的,但使用 Mat::at 检索时的值已损坏
- 运行时检查失败 #2 - 变量"e"周围的堆栈已损坏。发生
- 变量周围的堆栈'sortArray'已损坏
- 变量周围的堆栈'folderPath'已损坏
- 在为 iOS 构建 aws-sdk-cpp 时,cmake 上的 CXX 编译器错误已损坏
- 运行时检查失败 #2 - 变量周围的堆栈'...'已损坏
- AES-128 CFB-8解密的前16个字节已损坏
- 运行时检查失败 #2 - 变量"l1"周围的堆栈已损坏
- C++:此代码可以编译,但引发运行时检查失败 #2 - 围绕变量周围的堆栈'num'已损坏。发生
- 图像在本地主机上显示已损坏
- 检查工作正常的 CXX 编译器:/cygdrive/c/cygwin64/bin/clang++ -- 已损坏
- 数组变量周围的堆栈已损坏
- 运行时检查失败 - 变量周围的堆栈已损坏
- 串行端口的传入值有时已损坏或丢失
- 堆在realloc()上已损坏