champa

below code dosnt throw any error and printing goodmorning. Why strcpy working after deleting the str please explain why this happening

char *str = new char [100];

delete [ ] str ;

strcpy ( str ,"goodmoring");

cout <<str;




Re: Visual C++ Express Edition strcpy working even after deleting pointer.

LouArnold

This is likely a matter of you understanding the language.

"char *str" creates pointer to a char type. "str=new char[100] " seems to create an array of 100 bytes of type char - all, zero and put its address into str.

delete []str. does not delete the pointer, but it does delete the array. Note that both before and after this line of code, the pointer STILL contains the address of the now deleted array. You cannot delete the pointer manually. It is deleted when the object instance closes or when execution goes out of scope of the containing block of code.

strcpy(str,"goodmorning"); Works fine. Since str still has the array memory address in it, the string is happily copied over - to be overwritten at the next - and probably most unfortunate time :))

You should read up on smart pointers. Using such pointers helps avoid these problems by making sure that delete []str also sets the address in str to zero as well as deallocates the array.





Re: Visual C++ Express Edition strcpy working even after deleting pointer.

nobugz

The delete operator doesn't typically make the memory inaccessible. Unfortunately, it would be easier to debug C++ apps if it did. It just marks the block of memory as "unused" and add its to a linked list of empty blocks. Optionally merging adjacent empty blocks into one large empty block. Only when that merged block gets large enough does it release the memory pages.

This console mode program generated an assert at the 2nd "new", then printed "yes it does".

#include "stdafx.h"
#include <string.h>

int _tmain(int argc, _TCHAR* argv[])
{
char* str = new char[100];
delete[] str;
strcpy(str, "will it blow ");
char* str2 = new char[100];
strcpy(str2, "yes it does");
printf(str);
return 0;
}






Re: Visual C++ Express Edition strcpy working even after deleting pointer.

champa

thanks for the reply.

I again looked into the memory str is pointing to before and after deleting. its having memory even after deleting :) Wondering what  delete really mean by

 






Re: Visual C++ Express Edition strcpy working even after deleting pointer.

champa

yes,

got to know that delete really dont make the memory inaccessible. even after deleting its still have the memory address.

Thank you for the reply.