Zachery
Zachery

Reputation: 131

Why does this code (malloc) not generate heap corruption?

#include <iostream>

using namespace std;

struct A
{
    int a, b;
};

struct B
{
    int a;
};

int main()
{
    A * pa = (A *)malloc(sizeof(B));
    int c = 5;
    pa -> a = 3;
    cout << pa -> a << endl;
    pa -> b = 0;
    cout << pa -> b << endl;
    cout << c << endl;
    return 0;
}

I run this code with VC++ 2012. It doesn't generate any error message.

I think pa -> b will access memory block outbound. Heap corruption should occur! But actually, nothing happened in both debug and release modes.

But since int c immediately follows A * pa; I think in memory, pa -> b will access int c.

The output of the program is: 3 4 5

Can anyone help explain this?


If I add "free(pa);" at the end of the main: +under debug mode, it will cause HEAP CORRUPTION ERROR. +under release mode, nothing still happens.

Upvotes: 1

Views: 292

Answers (2)

NPE
NPE

Reputation: 500773

Undefined behaviour means that anything can happen. In particular, no diagnostic is required.

One practical way to find bugs of this type is by using a tool like Valgrind:

$ valgrind ./a.out
a=3
==37240== Invalid write of size 4
==37240==    at 0x100000E1D: main (test.c:22)
==37240==  Address 0x10001b184 is 0 bytes after a block of size 4 alloc'd
==37240==    at 0x5237: malloc (in /usr/local/Cellar/valgrind/3.8.1/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==37240==    by 0x100000DD2: main (test.c:19)
==37240== 
==37240== Invalid read of size 4
==37240==    at 0x100000E28: main (test.c:23)
==37240==  Address 0x10001b184 is 0 bytes after a block of size 4 alloc'd
==37240==    at 0x5237: malloc (in /usr/local/Cellar/valgrind/3.8.1/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==37240==    by 0x100000DD2: main (test.c:19)
==37240== 

There are similar tools for Windows: Is there a good Valgrind substitute for Windows?

Upvotes: 1

Dialecticus
Dialecticus

Reputation: 16769

Heap corruption can only be detected when you enter some heap function. In this case you enter a heap function only at the beginning, when heap is still uncorrupted. Try to delete structure pointed to pa before returning from main, and see what happens.

Upvotes: 0

Related Questions