This is my code
int main()
{
char *something = new char[10];
something = "test";
cout << something;
delete[] something;
return 0;
}
When I debug it it opens the application and gives me an error window saying Debug Assertion Failed: _CrtlsValidHeapPointer(block)
Thank you.
In this case something
is a pointer to character. In the second line you change the value of something
to point to the first character of "test" rather than what you expect, which is to place "test" in the memory pointed to by something
.
When you delete
you're trying to delete the memory that "test" is in, which read only memory.
In general you should consider using std::string
with C++
. If you're using char *
for some other reason look at strcpy
and strncpy