【发布时间】:2015-07-04 07:04:31
【问题描述】:
我有以下代码。
#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 会发生什么?我做了什么导致内存泄漏的事情吗?
【问题讨论】:
-
不应该在
free()调用之后调用_CrtDumpMemoryLeaks()吗? -
你输入了什么?您的程序会导致未定义的行为,尤其是对于某些输入。
-
我的输入总是“2+5”。我不知道关于内存泄漏的功能是如何工作的。我在 Microsoft 的网站上读到了这一点。它没有说要放它。
标签: c++ c visual-studio-2010 memory-leaks malloc