C++: This code compiles, but throws Run-Time Check Failure #2 - Stack around the variable 'num' was corrupted. occurred

Viewed 53

When the code executes the variable num get the value '9', then the error occurs.

char num = 'A';
int* pnum = (int *)#
*pnum = '9';

What does the error mean?

1 Answers

Casting and using a pointer like this is undefined behavior. You can't just take a pointer to a char and pretend that it's pointing to an int and expect it to work correctly. In all likelyhood the stack is getting corrupted because an int takes more memory than a char, so by doing *pnum = '9';, you're writing to invalid memory. char has size 1, but *pnum = '9'; will probably modify more memory than that (int commonly has size 4). So if there is 1 byte of memory reserved for the char on the stack, what are those other three bytes that it's modifying?

Use a char* to point to a char instead:

int main() {
    char num = 'A';
    char* pnum = #
    *pnum = '9';
    std::cout << num << std::endl;
}
Related