检测到堆损坏

Heap corruption detected

本文关键字:损坏 检测      更新时间:2023-10-16

>我有一个非常简单的代码,如下所示

#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 个字符。 这会导致分配的缓冲区溢出