简体   繁体   English

malloc导致内存泄漏

[英]Malloc cause memory leak

I have the following code.我有以下代码。

#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;
}

After malloc returns without a problem the function in the line with the comment prints in the output window in visual studio the next message:在 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.

When the program stops the visual detects heap corruption.当程序停止时,视觉检测到堆损坏。 Does anyone know what happens?有谁知道会发生什么? As far as i know there's nothing wrong with my code so what happens with malloc?据我所知,我的代码没有任何问题,那么 malloc 会发生什么? Did i do something that caused the memory leak?我是否做了一些导致内存泄漏的事情?

You should not attempt to detect memory leaks prior to releasing all memory.在释放所有内存之前,您不应尝试检测内存泄漏。 Calling _CrtDumpMemoryLeaks();调用_CrtDumpMemoryLeaks(); prior to free -ing everything that you have allocated is bound to detect false "leaks" that are simply memory in active use by your program.free之前,您分配的所有内容都必然会检测到错误的“泄漏”,这些错误的“泄漏”只是您的程序正在使用的内存。

Moving the check to the end will fix the problem:将支票移到最后将解决问题:

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

You should also add a check for strlen(input) to be 3 or more;您还应该检查strlen(input)是否为 3 或更多; otherwise, you could pass a negative number to malloc , which malloc would interpret as a large positive number;否则,您可以将负数传递给mallocmalloc会将其解释为一个很大的正数; this should never happen.这不应该发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM