【问题标题】:Memory Clobbering Error内存破坏错误
【发布时间】:2011-07-04 12:25:28
【问题描述】:

我有一小段代码。我使用-lmcheck 编译它,因为我正在尝试调试出现相同类似错误的代码。

运行此代码时出现此错误:

memory clobbered before allocated block

有人可以解释为什么free(ptr) 会抛出这个错误吗?

我还能如何释放指针?

谢谢。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define LEN 5


int main(int argc, char *argv[]){

    char *ptr = NULL;

    ptr = (char *) malloc(LEN+1);// +1 for string
    strcpy(ptr, "hello");

    int i = 0;
    for(i = 0; i<LEN; i++)
    {
        printf("ptr[%d] = %c\n", i, ptr[i]);
        ptr++;
    }
    free(ptr);


    return 0;
}

【问题讨论】:

标签: c memory-leaks malloc


【解决方案1】:

您正在递增ptr,因此更改了它指向的地址。你不能那样做。

在你的情况下,有一个单独的指针,比如说char * p = ptr 并使用p 进行操作,保持ptr 不变,以便以后可以free(ptr)

编辑再次查看您的代码,我发现您正在执行 ptr++ 而您不应该这样做。您正在访问数组中的字符,例如ptr[i],如果您弄乱了ptr 指针,您正在更改基地址,并且使用ptr[i] 访问字符可能会导致(并且将会导致)意外结果。

如果您只是删除该行 (ptr++),您的代码就会神奇地工作。 如果您想探索指针概念并尝试其他解决方案,您的代码可能如下所示:

int main(int argc, char *argv[]){

    char *ptr = NULL;
    char * p; 

    ptr = (char *) malloc(LEN+1);// +1 for string (please check for NULL)
    p = ptr;

    strcpy(ptr, "hello");

    int i = 0;
    while (*p) // note how I changed it to a while loop, C strings are NULL terminated, so this will break once we get to the end of the string. What we gain is that this will work for ANY string size.
    {
        printf("ptr[%d] = %c\n", i++, *p); // here i dereference the pointer, accessing its individual char
        p++;
    }
    free(ptr);


    return 0;
}

【讨论】:

  • 很好的解释!感谢您加倍努力。
【解决方案2】:

因为ptr 不再指向您分配的内存的基址。

【讨论】:

    【解决方案3】:

    此外,在增加 ptr 之后,表达式 ptr[i] 不会返回您可能期望的结果;这就是为什么输出以“hlo”开头的原因。

    【讨论】:

      【解决方案4】:

      在 cmets 中找到答案。 通常,当您分配一些内存时,内存管理框架会通过向分配的内存区域添加更多信息(可以说是页眉和页脚)来跟踪它。当您释放此内存时,会匹配相同的信息,以便检测任何不需要/无效的内存访问。

      int main(int argc, char *argv[]){
      
          char *ptr = NULL;
          char* temp = NULL;           // Have a temp pointer.
      
          ptr = (char *) malloc(LEN+1);// +1 for string
          strcpy(ptr, "hello");
      
          temp = ptr;                 // manipulate temp pointer instead of ptr itself
      
          int i = 0;
          for(i = 0; i<LEN; i++)
          {
              printf("ptr[%d] = %c\n", i, temp[i]);
              temp++;                 // Why you are incrementing this? Just to print, there is no need of this.
          }
          free(ptr);
      
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-19
        • 1970-01-01
        • 2010-09-06
        • 1970-01-01
        • 2011-10-03
        • 1970-01-01
        相关资源
        最近更新 更多