The program is written in C++, I was using
new
before with the same results and I figured that by using
malloc
instead of
new
I was ensuring that I was using the heap and not the stack.
I don't have a
free
or
delete
because I was under the impression that because
memBlock
is declared within a class function that it was automatically destroyed when the function ended.
After adjusting the program to use
new
and
delete
I am still getting similar problems, here are the valgrind examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
==23809== Invalid write of size 4
==23809== at 0x808346D: readFile(std::string, MemBlock&) (functions.h:270)
==23809== by 0x805C976: GameSys::load(GameVars&) (System.h:41)
==23809== by 0x80827CA: main (TheDestroyer.cpp:429)
==23809== Address 0x76e95f4 is 0 bytes after a block of size 4 alloc'd
==23809== at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==23809== by 0x805C8DF: GameSys::load(GameVars&) (System.h:35)
==23809== by 0x80827CA: main (TheDestroyer.cpp:429)
==23809==
==23809== Invalid read of size 4
==23809== at 0x8083476: readFile(std::string, MemBlock&) (functions.h:274)
==23809== by 0x805C976: GameSys::load(GameVars&) (System.h:41)
==23809== by 0x80827CA: main (TheDestroyer.cpp:429)
==23809== Address 0x76e95f4 is 0 bytes after a block of size 4 alloc'd
==23809== at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==23809== by 0x805C8DF: GameSys::load(GameVars&) (System.h:35)
==23809== by 0x80827CA: main (TheDestroyer.cpp:429)
...
...
...
9,216 bytes in 8 blocks are definitely lost in loss record 398 of 409
==23809== at 0x402B454: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==23809== by 0x8083480: readFile(std::string, MemBlock&) (functions.h:274)
==23809== by 0x8068FFF: O2D::load(GameVars&) (O2D.h:73)
==23809== by 0x80829FA: main (TheDestroyer.cpp:451)
| |
Line 270 is
memBlock.size = myFile.tellg();
which is giving and invalid write of size 4.
Line 274 is
memBlock.buffer = new char[memBlock.size];
which is giving an invalid read of size 4.
What I changed was:
MemBlock *memBlock = (MemBlock*) malloc(sizeof(MemBlock*));
is now:
MemBlock *memBlock = new MemBlock;
and:
memBlock.buffer = (char*) malloc(memBlock.size*sizeof(char*));
is now:
memBlock.buffer = new char[memBlock.size];
And at the end of the function that declares
memBlock
I added a
delete memBlock;
but it doesn't seem to have any impact on the results.