简体   繁体   中英

C++ Dynamic Memory Error

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

something = "test";

assigns your pointer to an address allocated using a static storage allocated literal. Your original pointer allocated dynamically gets lost.

To copy contents, use std::copy() .

You need to use strcpy to copy "test" into your array.

strcpy(something, "test"); // or even better user strncpy

Instead, you have:

something = "test";

The code about overwrites the pointer stored in the something variable with a new address. The address of a compiler generated string constant. Then delete [] is acting on this new address that doesn't point to the dynamically allocated memory returned by new.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM