堆在realloc()上已损坏

A heap has been corrupted on realloc()

本文关键字:已损坏 realloc 堆在      更新时间:2023-10-16

我正试图编写一个通用函数来调整大小和连接字符串,但在调用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正在更改,而不是由函数返回。