int main()
{
char *p;
p = malloc(10);
delete(p);
return;
}
Valgrind检测到什么是适当的错误?
答案 0 :(得分:1)
首先,此代码段提供了两个编译错误,
在函数'int main()'中:
错误:从'void *'到'char *'的无效转换[-fpermissive]
p = malloc(10);
^
错误:没有值的return语句,函数返回'int'[ - fpermissive]
返回;
使用这些更改更正代码,
使用malloc分配内存时进行类型转换,如下所示。 p =(char *)malloc(10);
main函数的返回类型是int,因此请相应地更改返回值,如此处所述。 返回0; //使用return 0,而不仅仅是return。
在使用删除操作之前,请对指针进行有效性检查,如下所示。 如果(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)