【问题标题】:Malloc cause memory leakmalloc 导致内存泄漏
【发布时间】: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


【解决方案1】:

您不应在释放所有内存之前尝试检测内存泄漏。在free 之前调用_CrtDumpMemoryLeaks();-ing 您分配的所有内容必然会检测到错误的“泄漏”,这些错误只是您的程序正在使用的内存。

将检查移到末尾将解决问题:

S=(char*)malloc(3);
N=(int*)malloc((strlen(input)-3)*sizeof(int));
free(S);
free(N);
_CrtDumpMemoryLeaks();  /* No memory leaks! */

您还应该添加一个检查 strlen(input) 是否为 3 或更多;否则,您可以将一个负数传递给mallocmalloc 会将其解释为一个很大的正数;这绝不应该发生。

【讨论】:

  • 传递给 malloc 的值将是一个很大的正数
  • 知道我明白。我读到这个功能的网站没有提到这一点。谢谢!!
  • @Csd 欢迎您。如果这回答了您的问题,请考虑通过单击旁边的灰色复选标记来接受答案。这将使其他网站访问者知道您的问题已解决,并为您赢得 Stack Overflow 上的新徽章。
猜你喜欢
  • 2021-07-23
  • 1970-01-01
  • 2016-11-14
  • 2015-07-06
  • 2014-06-07
  • 2013-11-20
  • 2011-10-28
  • 2016-01-18
  • 2012-12-13
相关资源
最近更新 更多