您编写的代码会泄漏。
==365== Memcheck, a memory error detector
==365== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==365== Using Valgrind-3.17.0.GIT and LibVEX; rerun with -h for copyright info
==365== Command: ./test
==365==
==365==
==365== HEAP SUMMARY:
==365== in use at exit: 8 bytes in 2 blocks
==365== total heap usage: 3 allocs, 1 frees, 72,712 bytes allocated
==365==
==365== 4 bytes in 1 blocks are definitely lost in loss record 1 of 2
==365== at 0x484D103: operator new(unsigned long) (vg_replace_malloc.c:342)
==365== by 0x10919E: main (in /petsc/test)
==365==
==365== 4 bytes in 1 blocks are definitely lost in loss record 2 of 2
==365== at 0x484D103: operator new(unsigned long) (vg_replace_malloc.c:342)
==365== by 0x1091CC: one() (in /petsc/test)
==365== by 0x1091A7: main (in /petsc/test)
==365==
==365== LEAK SUMMARY:
==365== definitely lost: 8 bytes in 2 blocks
==365== indirectly lost: 0 bytes in 0 blocks
==365== possibly lost: 0 bytes in 0 blocks
==365== still reachable: 0 bytes in 0 blocks
==365== suppressed: 0 bytes in 0 blocks
==365==
==365== For lists of detected and suppressed errors, rerun with: -s
==365== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
上面的注意事项我删除了两个打印调用,因为第一个调用 one() 两次以上,导致 2 个额外的泄漏
您永远不会直接存储one() 返回的指针,而是立即取消引用它。这具有丢弃该地址的效果。更好的方法是执行以下操作:
// two is an uninitialized pointer
int *two;
// Assign the returned pointer to two
two = one();
// Assign the value pointed to by two (and in effect one()) to three and use it
int three = *two;
functionThatExpectsAnInt(three);
// Alternatively use two directly, it points to valid memory whose value has not changed
functionThatExpectsAnInt(*two);
// Clean up resources from one()
delete two;
对于返回分配内存的函数,调用者是函数返回的资源的有效“所有者”。所以调用者必须要么释放资源,要么将它们传递给另一个函数。