Because it's not the right way of actually initializing the memory. You lost a pointer to allocated memory in createmem. When the call returned, the pointer to the actual memory was not returned in main because the int* myInt is a value copied from main. The int* integers in main is still NULL. C++ is a call by value language. If you want to change the value of integers in main, you have to pass it by reference. Anyway, here's your leak.
Code:
==6483== HEAP SUMMARY:
==6483== in use at exit: 20 bytes in 1 blocks
==6483== total heap usage: 1 allocs, 0 frees, 20 bytes allocated
==6483==
==6483== 20 bytes in 1 blocks are definitely lost in loss record 1 of 1
==6483== at 0x4C285EB: operator new[](unsigned long) (vg_replace_malloc.c:305)
==6483== by 0x40082D: main (foo.cpp:9)
==6483==
==6483== LEAK SUMMARY:
==6483== definitely lost: 20 bytes in 1 blocks
==6483== indirectly lost: 0 bytes in 0 blocks
==6483== possibly lost: 0 bytes in 0 blocks
==6483== still reachable: 0 bytes in 0 blocks
==6483== suppressed: 0 bytes in 0 blocks
==6483==
==6483== For counts of detected and suppressed errors, rerun with: -v
==6483== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
That's the line: myints = new int[5];
Also, if I try to dereference your pointer in main, we can see it clearly doesn't work:
Code:
#include <iostream>
using namespace std;
void createmem(int *myints);
void createmem(int *myints)
{
myints = new int[5];
}
int main()
{
int *integers = NULL;
createmem(integers);
integers[0] = 5; // Line I added
delete[] integers;
}
Valgrind output:
Code:
==6506== Invalid write of size 4
==6506== at 0x40082E: main (foo.cpp:17)
==6506== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==6506==
==6506==
==6506== Process terminating with default action of signal 11 (SIGSEGV)
==6506== Access not within mapped region at address 0x0
==6506== at 0x40082E: main (foo.cpp:17)
[...]
Segmentation fault