我对C++内存管理很陌生,因为与C不同,释放所有内存还有更多障碍.
我试图成功删除任何类型的矢量指针(即矢量*数据)
/**
* We test the program in accessing vectors
* with dynamic storage
**/
#include <iostream>
#include <vector> // you must include this to use vectors
using namespace std;
int main (void){
// Now let's test the program with new and delete
// for no memory leaks with vectors (type safe)
// however, just calling delete is not enough to free all memory
// at runtime
vector <int> * test_vect = new vector <int> (10,5);
// Print out …Run Code Online (Sandbox Code Playgroud) 当我在线阅读一些在线网站提供的代码时,我宁愿遇到一个我从未预料到的奇怪故障:变量突然改变其值而没有任何手动分配.
这是下面的代码:
int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file);
printf("rc is equal to %d\n", rc); // should print out 1
if (rc != 1) die("Failed to write Database.");
rc = fflush(conn->file);
printf("rc is equal to %d\n", rc); // should print out 0
if (rc == -1); die("Cannot flush database"); // error handling
// error comes up because rc suddenly changes to -1
Run Code Online (Sandbox Code Playgroud)
我不明白它是如何发生的,但是想知道为什么变量突然在C中突然发生变化.
代码来源:http: //c.learncodethehardway.org/book/learn-c-the-hard-waych18.html (Database_write下的堆栈和内存)
顺便说一下,我在Mac osx 10.6雪豹的终端上使用vim.