Reputation: 312
I am trying to allocate a two dimensional array dynamically and then after use, delete it. The code looks something 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.
Upvotes: 1
Views: 938
Reputation: 312
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
Upvotes: 0
Reputation: 9492
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:
See http://linux.die.net/man/3/strcpy for proper strcpy & strncpy parameters.
Upvotes: 1