- #1
tangodirt
- 54
- 1
I'm trying to plug up a memory leak in a simple C program that multiplies two matrices together. I've profiled my code with valgrind, and it reports leaked memory from within this function:
I believe the issue is that the *contiguousMemory variable is malloced, but never freed. So, I tried adding a line before the return matrix; line that calls: free(contiguousMemory), which closes the memory leak, but instead returns:
Any ideas for fixing this?
Code:
int ** AllocateMatrix(int size) {
int i = 0;
int *contiguousMemory = (int*) malloc(sizeof(int)*size*size);
int **matrix = (int**) malloc(sizeof(int*)*size);
for (i = 0; i < size; i++) {
matrix[i] = (int*) contiguousMemory+(i*size);
}
return matrix;
}
I believe the issue is that the *contiguousMemory variable is malloced, but never freed. So, I tried adding a line before the return matrix; line that calls: free(contiguousMemory), which closes the memory leak, but instead returns:
Code:
==14898== Invalid read of size 4
==14898== at 0x40102A: main (MatrixMultiply.c:252)
==14898== Address 0x4cae140 is 0 bytes inside a block of size 262,144 free'd
==14898== at 0x4A05A31: free (vg_replace_malloc.c:325)
==14898== by 0x400DD4: main (MatrixMultiply.c:179)
==14898==
==14898==
==14898== More than 10000000 total errors detected. I'm not reporting any more.
==14898== Final error counts will be inaccurate. Go fix your program!
==14898== Rerun with --error-limit=no to disable this cutoff. Note
==14898== that errors may occur in your program without prior warning from
==14898== Valgrind, because errors are no longer being displayed.
==17670== HEAP SUMMARY:
==17670== in use at exit: 0 bytes in 0 blocks
==17670== total heap usage: 6 allocs, 6 frees, 792,576 bytes allocated
==17670==
==17670== All heap blocks were freed -- no leaks are possible
==17670==
==17670== For counts of detected and suppressed errors, rerun with: -v
==17670== ERROR SUMMARY: 10000000 errors from 6 contexts (suppressed: 4 from 4)
Any ideas for fixing this?