开发者

Access Violation Message on Deleting Dynamically created two dimensional array

I am trying to allocate a two dimensional array dynamically and then after use, delete it. The code looks somethi开发者_如何学Pythonng like this:

func(char* pszError)
{

    //Initialize

    char ** ptr = new char*[1];

    // Some copying stuff in ptr[0]
    ptr[0] = new char[strlen(psError) + 1];
    strcpy(ptr[0], strlen(pszError) + 1, pszError); 

    delete[] ptr[0];

    delete[] ptr;

    return;

}

This looked harmless to me and shouldnt have given error. However, at the point delete[] ptr; its throwing me access violation.

Can anyone help me. I have done enough head banging on this.


The error lies with these lines:

ptr[0] = new char[strlen(psError) + 1];
strcpy(ptr[0], strlen(pszError) + 1, pszError);

Everything else looks correct to me. But the code shouldn't even compile with these errors. Some points to consider:

  • strcpy does not take 3 parameters. This code shouldn't even compile. This might mean one of the following:
    • You have a typo, and meant to use strncpy. If this is the case, then your 2nd and 3rd parameters are backwards which would cause the access violation.
    • You have overloaded the strcpy function with your own function that accepts 3 parameters. Please post the code for it if this is the case. It's probably better for you to use strncpy though.
  • "strlen(psError)" shouldn't compile either (missing a "z"). I assume you meant pszError, but if you have a global variable named psError then the incorrect amount of memory is probably being allocated.
  • If pszError is a bad pointer or isn't probably null-terminated, then the code would obviously crash.

See http://linux.die.net/man/3/strcpy for proper strcpy & strncpy parameters.


thanks for the help! We found the issue was as pointed by some of you, in the allocation. So, we should have checked after allocation if the pointer returned was proper. It never compalined while we did copy/etc. However, when the distructer tried to free the memory, it gave access violation then.

Regards,

Andy

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜