【问题标题】:"CRT detected that the application wrote to memory after end of heap buffer"? when I free memory in C“CRT 检测到应用程序在堆缓冲区结束后写入内存”?当我在 C 中释放内存时
【发布时间】:2018-04-03 10:22:24
【问题描述】:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
    printf("Input 10 string\n");
    char** inputStr = (char**)malloc(sizeof(char*) * 10);
    for (int i = 0; i < 10; i++) {
        char str[16];
        int len = strlen(str);
        printf("String %d : ", i + 1);
        scanf("%s", str);
        *(inputStr + i) = (char*)malloc(sizeof(char) * (strlen(str) + 1));
        strcpy(*(inputStr + i), str);
    }

    /*
    do something
    */

    for (int i = 0; i < 10; i++) {
        free(*(inputStr + i));
    }
    free(inputStr);
    return 0;
}

当我在 VisualStudio 2017 中执行此代码时,出现错误,显示消息“CRT 检测到应用程序在堆缓冲区结束后写入内存”。

我删除了使用'free'关键字的代码部分,然后它可以正常工作。

但是我了解到,在“malloc”之后使用“free”是必不可少的。那么我怎样才能正确释放内存???

【问题讨论】:

  • 1) 删除int len = strlen(str); 2) scanf("%s", str); --> scanf("%15s", str);
  • 尝试注释掉 do-something 的一部分。

标签: c


【解决方案1】:

应用程序在堆缓冲区结束后写入内存

这听起来像是您的程序在 inputStr 指针数组的末尾之后写入了内存,或者可能在单个字符串缓冲区的末尾之后写入了内存。但是,您发布的代码似乎没有这个问题。也许您无意中做了超出/* do something */ 部分中这些缓冲区之一的末尾的操作?

正如 BLUEPIXY 所暗示的,您确实存在潜在的堆栈缓冲区溢出问题:如果您将超过 15 个字符读入 str,那么您将覆盖堆栈内存。而当str的内容是未初始化的栈垃圾时,调用strlen(str)也是无稽之谈。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多