内存破坏错误 [英] Memory Clobbering Error

查看:23
本文介绍了内存破坏错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小段代码.我用 -lmcheck 编译它,因为我正在尝试调试一个代码,但我有同样的类似错误.

I have a small piece of code. I compiled it with -lmcheck as I am trying to debug a code where I have the same similar error.

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

I get this error when I run this code:

memory clobbered before allocated block

谁能解释一下为什么 free(ptr) 会抛出这个错误?

Can someone explain the reason why free(ptr) will throw me this error?

我还能如何释放指针?

谢谢.

#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
", i, ptr[i]);
        ptr++;
    }
    free(ptr);


    return 0;
}

推荐答案

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

You are incrementing ptr, therefore changing the address that it points to. You can't do that.

在你的情况下,有一个单独的指针,比方说 char * p = ptr 并用 p 做你的操作,让 ptr 保持不变你可以稍后free(ptr).

In your case, have a separate pointer, let's say char * p = ptr and do your operations with p leaving ptr intact so you can free(ptr) later.

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

EDIT Taking a second look at your code, I found that you are doing ptr++ when you shouldn't. You are accessing the characters in the array like ptr[i], if you mess with the ptr pointer, you are changing the base address and accessing the characters with ptr[i] can lead (and will lead) to unexpected results.

如果您简单地删除该行 (ptr++),您的代码将神奇地工作.如果您想探索指针概念并尝试另一种解决方案,您的代码可能如下所示:

If you simply remove that line (ptr++) your code will magically work. If you want to explore the pointer concept and try another solution, your code could look something like this:

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
", i++, *p); // here i dereference the pointer, accessing its individual char
        p++;
    }
    free(ptr);


    return 0;
}

这篇关于内存破坏错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆