When I run the .exe being created with the below code in debug mode , it shows some assertion failure and the programme crashes But when i run the same exe created from the rele
void main
is wrong. main
returns int
. No exceptions.delete[] "Hello"
. "Hello"
is a string literal; you can't delete
it. char *buf = new char[5]; //pre-allocated buffer
Here you define a pointer, and initialize it to point to a dynamically allocated buffer with room for 5 characters.
buf = "Hello";
Here you initialize the pointer to point to the beginning of a string literal.
delete [] buf;
Here you delete[] the buf pointer, but the buf pointer no longer points to anything you new[]'d up, it points to the string literal. You can only delete/delete[] a pointer that points to something you got from new/new[]. So you get undefined behavior, and likely crash
You likely meant to copy the content of your string into the buffer you new[]'d. Remember to account for the nul terminator:
int main()
{
char *buf = new char[6]; //pre-allocated buffer
strcpy(buf, "Hello");
delete [] buf;
getchar();
//cout<<buf;
//string *p = new (buf) string("hi"); //placement new
//string *q = new string("hi"); //ordinary heap allocation
}
Though, in C++, you'd rather use std::string from #include <string>
;
std::string = "Hello";
You're trying to deallocate the character-string literal "Hello"
. This line:
buf = "Hello";
redirects the pointer buf
to point at the literal "Hello"
. You probably meant to do this:
char *buf = new char[6]; //need one extra space for terminating NUL character
strcpy(buf, "Hello");
char *buf = new char[6]; //pre-allocated buffer
strncpy(buf, "hello", 6);
delete [] buf;
buf = "hello"; would change the buf's value, from a pointer to new char[6] To a pointer point to "hello", a block of memory not in heap.
When you do this:
buf = "Hello";
You're basically changing the pointer value (memory address) at which buf
points to a read-only memory area, because "Hello"
is a string literal and therefore is stored in read-only memory.
Then you attempt to free that memory, hence the crash.
Also, "Hello"
is 6-bytes long, not 5.
Because undefined behavior means anything can happen. The problem is that buf = "Hello"
assigns the address of a string literal to buf
, then tries to delete that literal. When compiled in debug mode the checking code sees that the address can't be deleted; in release mode that check isn't done, and the delete just stomps on something that isn't critical.