C/C++ 错误笔记-如果要释放内存,必须拿到内存的首地址进行释放

例:修改字符串的第三个字母为a

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#pragma warning(disable:4996)


void main() {


    char *p = (char *)malloc(100);
    strcpy(p,"123456789");

    p = p + 2;
    *p = 'a';
    free(p);

    system("pause");

}

运行,VS报下列错误:

出现这个问题的原因是,C语言规定:如果要释放内存,必须拿到内存的首地址进行释放

而p指针在释放之前,进行了移位操作,不再指向首地址,因此程序发生crash。解决办法:只需要保存首元素的地址用来释放即可。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#pragma warning(disable:4996)


void main() {


    char *p = (char *)malloc(100);
    strcpy(p,"123456789");
    char *pHeader = p;

    p = p + 2;
    *p = 'a';
    printf("%s
", pHeader);
    free(pHeader);

    system("pause");

}

运行结果:

原文地址:https://www.cnblogs.com/yongdaimi/p/6764109.html