今天我试图从这里解决一个测验,当我到达问题 3 时,有以下代码:
#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 );
}
问题是:
在 C 程序上方选择正确的语句:
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
因为这条线:
free(*ppInt2);
据我了解,这表明不会出现编译或运行时错误,我决定
free(*ppInt2)
是不正确的。
但是因为这里没有编译/运行时错误,所以会出现 AnswersB
和C
错误。
作者说接受的答案是:
D - No issue with any of the malloc() and free() i.e. no compile/run time error.
现在这是我的问题,为什么没有问题,因为这样做:
free( *ppInt2 );
Valgrind 报告:
==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)
我认为正确的free
调用应该是:
free( ppInt2 );
测试Linux mint 19
,GCC-8
和valgrind-3.13.0