相关疑难解决方法(0)

内存Clobbering错误

我有一小段代码.我编译它时-lmcheck,我正在尝试调试代码,我有相同的类似错误.

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

memory clobbered before allocated block
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么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;
}
Run Code Online (Sandbox Code Playgroud)

c malloc memory-leaks

5
推荐指数
1
解决办法
5400
查看次数

标签 统计

c ×1

malloc ×1

memory-leaks ×1