以下是代码的简化版本,我删除了与问题无关的所有内容。
#include <iostream>
#define N 3
int main() {
int *input;
int **cl;
input = new int[N];
cl = new int*[N];
for(int i = 0; i < N; i++) {
cl[i] = new int[N];
}
for(int i = 0; i < N; i++) {
delete[] cl[i];
}
delete[] cl;
delete[] input;
return 0;
}
valgrind输出:
==5782== HEAP SUMMARY:
==5782== in use at exit: 72,704 bytes in 1 blocks
==5782== total heap usage: 6 allocs, 5 frees, 72,776 bytes allocated
==5782==
==5782== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==5782== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5782== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==5782== by 0x40104E9: call_init.part.0 (dl-init.c:72)
==5782== by 0x40105FA: call_init (dl-init.c:30)
==5782== by 0x40105FA: _dl_init (dl-init.c:120)
==5782== by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==5782==
==5782== LEAK SUMMARY:
==5782== definitely lost: 0 bytes in 0 blocks
==5782== indirectly lost: 0 bytes in 0 blocks
==5782== possibly lost: 0 bytes in 0 blocks
==5782== still reachable: 72,704 bytes in 1 blocks
==5782== suppressed: 0 bytes in 0 blocks
==5782==
==5782== For counts of detected and suppressed errors, rerun with: -v
==5782== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
我刚开始学习C ++,也许有一些我看不到的愚蠢错误。
我知道我还应该检查一下分配时是否没有“内存不足”错误,但我忽略它以便代码更清晰。我也知道我可以使用例如向量并不关心分配,但我仍然担心我做错了什么。
答案 0 :(得分:1)
C ++为您提供了为您封装内存管理的工具。
#include <iostream>
#include <vector>
int main() {
// read the size for the vectors
int n;
std::cin >> n >> '\n';
// allocate vector with n elements
auto input = std::vector<int>{n};
// read the elements
for(int i = 0; i < n; i++) {
std::cin >> std::setw(1) >> input[i];
}
// print them
for(const auto& d : input) {
std::cout << d << std::endl;
}
// allocate the vectors and store 1 in each field.
auto Cl = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}};
auto Cr = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}};
return 0;
// will safely release all the memory here.
}
这看起来更像C ++,而不像C语言。向量将自动为您处理所有内存管理。
注意:我没有测试过这段代码,所以它可能包含一些错误。我假设C ++ 11语法,但是也应该很容易将代码更改为旧的C ++语法。
答案 1 :(得分:0)
现在您已经添加了valgrind输出,它显然与在此处有答案的问题相同:Valgrind: Memory still reachable with trivial program using <iostream>
简短的故事是,导致该报告的不是您的代码。你可以删除main()
中的所有内容,然后返回,valgrind仍然会泄漏。
阅读该问题的已接受答案以获得解释。