我有以下代码。
#include<stdio.h>
#include<string.h>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
int main(){
int *N=NULL;
char *S=NULL,input[50],*Par=NULL,T='^';
printf("Give me the equation: ");
scanf("%s",input);
printf("\n%d",strlen(input));
S=(char*)malloc(3);
N=(int*)malloc((strlen(input)-3)*sizeof(int));
_CrtDumpMemoryLeaks(); /* Memory leak detected! */
free(S);
free(N);
return 0;
}
在 malloc 正常返回后,注释行中的函数将在 Visual Studio 的输出窗口中打印下一条消息:
Detected memory leaks!
Dumping objects ->
c:\users\manos\documents\visual studio 2010\projects\gcjgcjc\gcjgcjc\gdjjj.cpp(17) : {60} normal block at 0x00A343F8, 16 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
c:\users\manos\documents\visual studio 2010\projects\gcjgcjc\gcjgcjc\gdjjj.cpp(16) : {59} normal block at 0x00A31B30, 3 bytes long.
Data: < > CD CD CD
Object dump complete.
当程序停止时,视觉会检测到堆损坏。 有谁知道会发生什么?据我所知,我的代码没有任何问题,那么 malloc 会发生什么情况?我是否做了什么导致内存泄漏的事情?
最佳答案
在释放所有内存之前,不应尝试检测内存泄漏。调用_CrtDumpMemoryLeaks();
之前free
-您分配的所有内容必然会检测到错误的“泄漏”,这些泄漏只是您的程序正在积极使用的内存。
将检查移到末尾将解决问题:
S=(char*)malloc(3);
N=(int*)malloc((strlen(input)-3)*sizeof(int));
free(S);
free(N);
_CrtDumpMemoryLeaks(); /* No memory leaks! */
您还应该添加对 strlen(input)
的检查为 3 个或更多;否则,您可以将负数传递给 malloc
,其中malloc
会被解释为一个大的正数;这绝对不应该发生。
关于c++ - malloc导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31217942/