简体   繁体   中英

What happens when assigning a value to non-allocated memory?

int main()
{
    char* p = new char('a');
    *reinterpret_cast<int*>(p) = 43523;

    return 0;
}

This code runs fine but how safe is it? It should have only allocated one byte of memory but it doesn't seem to be having any problem filling 4 bytes with data. What can happen with the other 3 bytes that are not allocated?

The code is not safe. Your program has undefined behaviour. Anything at all could happen.

The code causes heap buffer overflow. You're overriding memory which you don't own and can be in use in other parts of the program.

char* p = new char('a');

ASCII code of 'a' is 97, so this is equivalent to:

char* p = new char(97);

Single character (1 byte) space is allocated with *p='a' Now, you are trying to put more than 1-byte value, that's certainly risky, even if this works, I mean runs without any segmentation fault. You are overwriting some other parts of memory that you don't own or even if own, must be for some other purpose.

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