检测到堆损坏
Heap corruption detected
>我有一个非常简单的代码,如下所示
#include <iostream>
struct mystruct
{
char *m1;
};
void pass(char **, const char *);
int _tmain(int argc, _TCHAR* argv[])
{
char *p = NULL;
pass (&p, "hello");
struct mystruct *mP = NULL;
mP = new mystruct;
pass ( &mP->m1, "hi");
//std::cout << mP->m1;
return 0;
}
void pass (char **p1, const char *q1)
{
*p1 = new char (3);
*p1[2] = ' ';
strcpy (*p1,q1);
std::cout << strlen (*p1);
std::cout << *p1;
delete []*p1;
}
并在达到delete[]
时heap corruption detected!
获取错误...请帮忙!!
*p1 = new char (3);
分配 1 个字符并使用值 3 对其进行初始化。
你的意思是
*p1 = new char [3]; //square brackets
更新:
另一个错误是这一行
*p1[2] = ' ';
虽然这一行是完全不必要的(strcpy 会处理你关心的事情(,但这是错误的,因为 [] 和 * 的优先级。你的意思是
(*p1)[2] = ' ';
在pass
中,您尝试为 p1
分配 3 个字符,但随后您将一个字符串复制到其中,strcpy
比这更长。 您需要将q1
的长度传递到pass
并相应地分配。
另外,您需要做*p1 = new char[SIZE];
其中SIZE
是一个足够大的值,可以将字符串存储在q1
中。
*p1 = new char (3);
调用 char 构造函数并分配一个 char。
strcpy (*p1,q1);
您正在复制 "hello",即 6 个字符。 这会导致分配的缓冲区溢出
相关文章:
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 删除字符串后C++检测到堆损坏
- 检测到堆损坏(字符串导致堆损坏)|C++
- 在C++中检测到堆损坏错误
- C++ 内存损坏检测
- 如何修复检测到堆损坏:正常阻止后
- 在复制 delete[] 数组后在 C++ 中检测到堆损坏
- 从检测到 glibc 正常退出 - malloc():内存损坏
- 编译器如何检测内存损坏
- 排序程序的错误(检测到堆损坏)
- 正常块错误后检测到的堆损坏
- C++ 删除数组时检测到堆损坏
- 调试错误,在C++中检测到堆损坏
- 检测到堆损坏(类方法)
- 在普通块(#164)之后检测到堆损坏
- jemalloc未检测到内存损坏
- 检测到合并排序堆损坏
- 堆损坏检测(模拟动态数组与静态数组)
- 堆损坏检测:在正常块之后(#153)
- QwtPlot - 堆损坏检测