c++ - malloc导致内存泄漏

标签 c++ c visual-studio-2010 memory-leaks malloc

我有以下代码。

#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/

相关文章:

c++ - 如何配置概率占用图人员检测器

c++ - 是否可以在 C++ 中使用非默认构造函数创建模板实例?

visual-studio - 让 Doxygen 和 MSVC TODO 标签协同工作

.net - F#实现接口(interface),多个参数,出现错误,此覆盖需要不同数量的

javascript - Visual Studio 2010 阻止对某些文件进行 JScript 调试

c++ - 用于 mysql 的异步 C++ 连接器

c++ - 在 Solaris 上,连续内存分配不会减小镜像大小

c - 原型(prototype)内核和模块

java - 是否可以为 Java 中的 C 程序打印诊断信息?

c - 当子进程上有 SIGINT (Crtl+c) 时,waitpid 返回 0