我是Windows平台上的C++程序员.我正在使用Visual Studio 2008.
我通常在内存泄漏的代码中结束.
通常我通过检查代码发现内存泄漏,但它很麻烦,并不总是一个好方法.
由于我买不起付费内存泄漏检测工具,我希望你们建议尽可能避免内存泄漏的方法.
我正在尝试memcheck我写的C python扩展,但是我在设置valgrind以使用python时遇到了麻烦.我真的很感激一些建议.仅供上下文使用,这是Ubuntu 13.10,python 2.7.5+和valgrind 3.8.1.
根据Readme.valgrind我的建议,我做了以下.
1)用.下载python源码
sudo apt-get build-dep python2.7
apt-get source python2.7
Run Code Online (Sandbox Code Playgroud)
2)应用代码补丁,即"在Objects/obmalloc.c中取消注释Py_USING_MEMORY_DEBUGGER".
3)应用抑制补丁,即"取消注释Misc/valgrind-python.supp中的行,以抑制PyObject_Free和PyObject_Realloc的警告"
4)编译python与
./configure --prefix=/home/dejan/workspace/python --without-pymalloc
make -j4 install
Run Code Online (Sandbox Code Playgroud)
请注意,我做了2和3,而README.valgrind说做2或3 ...更多不能伤害.
现在,让我们在一些示例python代码中对此进行测试 test.py
print "Test"
Run Code Online (Sandbox Code Playgroud)
让我们用这个脚本在python上运行valgrind
valgrind --tool=memcheck --leak-check=full --suppressions=python2.7-2.7.5/Misc/valgrind-python.supp bin/python test.py
Run Code Online (Sandbox Code Playgroud)
出乎意料的是,仍然有来自valgrind的大量报告,其中第一个报告(以及更多关注报告)
==27944== HEAP SUMMARY:
==27944== in use at exit: 857,932 bytes in 5,144 blocks
==27944== total heap usage: 22,766 allocs, 17,622 frees, 4,276,934 bytes allocated
==27944==
==27944== 38 bytes in 1 blocks are possibly lost in loss record 24 of 1,343
==27944== …Run Code Online (Sandbox Code Playgroud) 这是SDL计划:
#include <SDL/SDL.h>
int main(int argc, char** argv){
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16, SDL_HWSURFACE);
SDL_Quit();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用命令编译:
g++ -o test test.cpp -lSDL
Run Code Online (Sandbox Code Playgroud)
这是valgrind的输出:
christian@christian-laptop:~/cpp/tetris$ valgrind --leak-check=full ./test
==3271== Memcheck, a memory error detector
==3271== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==3271== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info
==3271== Command: ./test
==3271==
==3271==
==3271== HEAP SUMMARY:
==3271== in use at exit: 91,097 bytes in 1,258 blocks
==3271== total …Run Code Online (Sandbox Code Playgroud) 我正在尝试将名称分配给 TCP 服务器中的客户端,但该strcpy()功能给了我一个分段错误。
struct clients{
int client_fd;
char* name;
struct clients* next;
}
struct clients* first;
first->client_fd = 1;
first->name = NULL;
memset(&first->name, 0, sizeof(first->name));
first->name = (char*)malloc(100*sizeof(char));
strcpy(first->name, "User");
first->next = NULL;
Run Code Online (Sandbox Code Playgroud) 我是C的初学者.我在想,这是怎么回事malloc.这是一个示例代码,我在试图理解它的工作时写了.
码:
#include<stdio.h>
#include<stdlib.h>
int main() {
int i;
int *array = malloc(sizeof *array);
for (i = 0; i < 5; i++) {
array[i] = i+1;
}
printf("\nArray is: \n");
for (i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
free(array);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
Array is:
1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)
在上面的程序中,我只为1个元素分配了空间,但是数组现在包含5个元素.因此,当程序顺利运行而没有任何错误时,目的是什么realloc().
谁有人解释原因?
提前致谢.