Today I tried to solve a Quiz from Here and when I reached the Question 3, there was the following code:
#include <stdlib.h>
int main(void){
int *pInt;
int **ppInt1;
int **ppInt2;
pInt = (int*)malloc(sizeof(int));
ppInt1 = (int**)malloc(10*sizeof(int*));
ppInt2 = (int**)malloc(10*sizeof(int*));
free( pInt );
free( ppInt1 );
free( *ppInt2 );
}
And the Question was:
Choose the correct statement w.r.t. above C program:
A - malloc() for ppInt1 and ppInt2 isn’t correct. It’ll give compile time error.
B - free(*ppInt2) is not correct. It’ll give compile time error.
C - free(*ppInt2) is not correct. It’ll give run time error.
D - No issue with any of the malloc() and free() i.e. no compile/run time error
Because of this line:
free(*ppInt2);
Which for what I understand suggests that, there will be no compile or run time error, I decided that
free(*ppInt2)
is not correct.
But because there is no compile/run time errors here, makes Answers B
and C
wrong.
The Author says that the accepted Answer is:
D - No issue with any of the malloc() and free() i.e. no compile/run time error.
Now here is my Question, why is there no issue, because doing this:
free( *ppInt2 );
Valgrind reports:
==9468== Memcheck, a memory error detector
==9468== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==9468== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==9468== Command: ./program
==9468==
==9468== Conditional jump or move depends on uninitialised value(s)
==9468== at 0x4C30CF1: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9468== by 0x1086C1: main (program.c:14)
==9468== Uninitialised value was created by a heap allocation
==9468== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9468== by 0x108696: main (program.c:10)
==9468==
==9468==
==9468== HEAP SUMMARY:
==9468== in use at exit: 80 bytes in 1 blocks
==9468== total heap usage: 3 allocs, 2 frees, 164 bytes allocated
==9468==
==9468== 80 bytes in 1 blocks are definitely lost in loss record 1 of 1
==9468== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==9468== by 0x108696: main (program.c:10)
==9468==
==9468== LEAK SUMMARY:
==9468== definitely lost: 80 bytes in 1 blocks
==9468== indirectly lost: 0 bytes in 0 blocks
==9468== possibly lost: 0 bytes in 0 blocks
==9468== still reachable: 0 bytes in 0 blocks
==9468== suppressed: 0 bytes in 0 blocks
==9468==
==9468== For counts of detected and suppressed errors, rerun with: -v
==9468== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
I thought that the right free
call should be:
free( ppInt2 );
Tested on Linux mint 19
, GCC-8
and valgrind-3.13.0