开发者

Heap corruption detected

I have a very simple code like below

#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] = '\0';
    strcpy (*p1,q1);
    st开发者_Go百科d::cout << strlen (*p1);
    std::cout << *p1;
    delete []*p1;
}

and get the error heap corruption detected! when delete[] is reached ...Please help !!!


*p1 = new char (3);

allocates 1 char and initializes it with value 3.

You meant

*p1 = new char [3]; //square brackets

Update:

The other error is this line

*p1[2] = '\0';

Although this line is completely unnecessary (strcpy will take care of what concerns you) this is wrong bacause of precedence of [] and *. You meant

(*p1)[2] = '\0';


In pass you are trying to allocate 3 characters for p1, but then you are copying a string to it with strcpy thats longer than that. You need to pass the length of q1 into pass and allocate accordingly.

Also, you need to do *p1 = new char[SIZE];

Where SIZE is a value big enough to store the string in q1.


*p1 = new char (3);

calls char constructor and allocates one char. then in

strcpy (*p1,q1);

you are copying "hello" which is 6 char. this leads to allocated buffer overflow

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜