int main()
{
char *p;
p = malloc(10);
delete(p);
return;
}
Valgrind检测到的适当错误是什么?
-
首先,这个代码片段给出了两个编译错误,
在函数"int main()"中:错误:从"void*"到"char*"的转换无效[-fpermission]p=malloc(10)
^错误:函数中没有值的return语句返回"int"[-fpermission]回来 -
通过这些更改更正代码,
-
使用malloc分配内存时键入cast,如下所示。p=(char*)malloc(10);
-
main函数的返回类型是int,因此相应地更改返回值,如这里所述。返回0;//使用return 0,而不仅仅是return。
-
在使用删除操作之前,请对指针进行有效性检查,如下所示。if(p)删除(p);
-
-
经过上述更改,并在成功编译上述代码后。使用valgrind工具运行上述样品。因此,代码中没有任何问题,所以valgrind没有发现任何问题。以下是valgrind输出的样本。
Valgrind输出:
==30050== Memcheck, a memory error detector
==30050== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==30050== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==30050== Command: ./valgrindtest
==30050==
main Start
==30050== Mismatched free() / delete / delete []
==30050== at 0x4C2C18D: operator delete(void*) (vg_replace_malloc.c:576)
==30050== by 0x4006E0: main (valgrindtest.cpp:16)
==30050== Address 0x5a1b040 is 0 bytes inside a block of size 10 alloc'd
==30050== at 0x4C2ABE3: malloc (vg_replace_malloc.c:299)
==30050== by 0x4006C2: main (valgrindtest.cpp:11)
==30050==
main End
==30050==
==30050== HEAP SUMMARY:
==30050== in use at exit: 0 bytes in 0 blocks
==30050== total heap usage: 1 allocs, 1 frees, 10 bytes allocated
==30050==
==30050== All heap blocks were freed -- no leaks are possible
==30050==
==30050== For counts of detected and suppressed errors, rerun with: -v
==30050== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)