有一个返回指针(任何类型)的函数,如果我在调用函数时没有存储指针,会发生什么? 在这种情况下,函数是否仍会返回指针?如果是,那么是否存在内存泄漏,因为我没有释放分配的内存?
以下面的代码为例:
int * testfunc()
{
int * a=new int();
return(a);
}
int main()
{
testfunc();
return(0);
}
答案 0 :(得分:3)
是的,您必须手动释放分配了new
,new[]
,malloc()
和calloc()
的每个内存块。该方法仍将返回一个指针,它指向有效的内存,但你不能使用或释放它。在C ++中,您几乎总是按值返回,move semantics将处理动态内存。
答案 1 :(得分:1)
是的,它会泄漏内存。
当函数退出时,函数作用域中的指针变量将被销毁,但指针已分配的数据将保留在内存中。 该函数返回数据所在的地址。
如果这确实是您的函数要执行的操作,那么您仍然可以使用返回的地址删除数据
int *pi = testfunc();
delete pi;
然后在程序退出时不会出现内存泄漏,但是在函数中是否存在内存泄漏问题。
答案 2 :(得分:-3)
我使用语句(valgrind --leak-check=full --show-reachable=yes --track-origins=yes ./test)
对问题中给出的代码(使用'-g'选项编译后)运行了valgrind
以下是输出
==59142== Memcheck, a memory error detector
==59142== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==59142== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==59142== Command: ./test
==59142==
==59142==
==59142== HEAP SUMMARY:
==59142== in use at exit: 4 bytes in 1 blocks
==59142== total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==59142==
==59142== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==59142== at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==59142== by 0x4006D3: testfunc() (test.cpp:7)
==59142== by 0x4006EF: main (test.cpp:13)
==59142==
==59142== LEAK SUMMARY:
==59142== definitely lost: 4 bytes in 1 blocks
==59142== indirectly lost: 0 bytes in 0 blocks
==59142== possibly lost: 0 bytes in 0 blocks
==59142== still reachable: 0 bytes in 0 blocks
==59142== suppressed: 0 bytes in 0 blocks
==59142==
==59142== For counts of detected and suppressed errors, rerun with: -v
==59142== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)
这清楚地表明存在内存泄漏。