【发布时间】:2016-08-10 03:06:13
【问题描述】:
开始了解 C++,并尝试将类模板化以使用结构的 Ints 和 Pointers。 输出符合预期,但使用 valgrind 进行测试时,似乎有一个内存韭菜,来自未释放的内存。
我相信这与我在类 init 中声明列表变量的方式有关。
我缺少什么,我该如何解决? 谢谢。
#include <stdio.h>
template <class T>
class List {
T* list;
public:
int length;
List(int len) {
list = new T[len];
length = len;
}
virtual ~List() {
delete[] list;
}
T get(int index) {
return list[index];
}
void set(int index, T val) {
list[index] = val;
}
};
/*
You shouldn't change the code below, unless you want to _temporarily_ change the main function while testing.
Change it back when you're done.
*/
typedef struct Point_ {
int x;
int y;
} Point;
int main(){
List<int> integers(10);
for(int i = 0; i < integers.length; i++){
integers.set(i, i * 100);
printf("%d ", integers.get(i));
}
printf("\n"); // this loop should print: 0 100 200 300 400 500 600 700 800 900
List<Point *> points(5);
for(int i = 0; i < points.length; i++) {
Point *p = new Point;
p->x = i * 10;
p->y = i * 100;
points.set(i, p);
printf("(%d, %d) ", points.get(i)->x, points.get(i)->y);
delete p;
}
printf("\n"); // this loop should print: (0, 0) (10, 100) (20, 200) (30, 300) (40, 400)
}
像这样用 g++ 编译:
g++ -Wall p2_templates.cpp -o p2_templates
在这个命令中使用了 valgrind:
valgrind --tool=memcheck ./p2_templates
从 valgrind 得到这个结果:
==22396== Memcheck, a memory error detector
==22396== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==22396== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==22396== Command: ./p2_templates
==22396==
0 100 200 300 400 500 600 700 800 900
(0, 0) (10, 100) (20, 200) (30, 300) (40, 400)
==22396==
==22396== HEAP SUMMARY:
==22396== in use at exit: 72,704 bytes in 1 blocks
==22396== total heap usage: 9 allocs, 8 frees, 73,848 bytes allocated
==22396==
==22396== LEAK SUMMARY:
==22396== definitely lost: 0 bytes in 0 blocks
==22396== indirectly lost: 0 bytes in 0 blocks
==22396== possibly lost: 0 bytes in 0 blocks
==22396== still reachable: 72,704 bytes in 1 blocks
==22396== suppressed: 0 bytes in 0 blocks
==22396== Rerun with --leak-check=full to see details of leaked memory
==22396==
==22396== For counts of detected and suppressed errors, rerun with: -v
==22396== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
【问题讨论】:
-
为什么不直接使用
vector? -
为什么
main中的new和delete业务无用?顺便说一句,#include <stdio.h>应该是#include <cstdio>,前者是合法的,但自第一个标准以来已被弃用。另外,请查看<iostream>,它是标准 C++ I/O。 -
@jaggedSpire 无论如何都不会伤害到链接到文档,他越早避开这个自制的东西越好。老实说,我对麻省理工学院这样的机构的期望更高,但另一方面,它是一个“学习 C/C++ 的网站”。 ://
-
@ROX 希望如此,尽管
typedefedstruct并没有给我太多希望,他们在类中与 C 大相径庭。 -
等等,OP,你在什么系统上运行?如果是 Mac OS X,请尝试注释掉
printf语句并再次运行。 valgrind occasionally finds potential leaks 与标准输出 on that OS.
标签: c++ templates memory-leaks valgrind