Tuesday, May 20, 2008

Mismatched Array/New Delete

This is a example program which shows a common coding error, that I have seen quite a bit - mismatching scalar vs vector new/delete.

Raymond's blog entry has more detail about what can happen when you do this by mistake. To make a long story short - memory leak or heap corruption.

Here is an example program which shows these errors:

#include
#include
#include


int main()
{
char *tmpArray = new char[17];
strcpy(tmpArray,"This is tmpArray");
printf("tmpArray=%s\n",tmpArray);

char *charArray=new char[18];
strcpy(charArray,"This is charArray");
printf("charArray=%s\n",charArray);
delete charArray;

char * character = new char;
*character = 'a';
printf("character=%c\n",*character);
delete [] character;

printf("tmpArray=%s\n",tmpArray);
free(tmpArray);

printf("Press Enter to continue");
int a = getchar();

}

No comments: