gdb free invalid pointer问题解决
1,代码问题:
新建 gdb.c
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
//#include <sharemem.h>
void fun(uint8_t* p)
{
uint8_t a = 100;
*p = a;
}
void fun1(int* p)
{
int b = 999;
*p = b;
}
int main()
{
uint8_t *p = (uint8_t*)malloc(sizeof(uint8_t*));
uint8_t a;
p = &a;
fun(p);
printf("a=%d\n",a);
free(p);
p = NULL;
int* q1 = (int*)malloc(sizeof(int*));
int g;
q1 = &g;
fun1(q1);
printf("g=%d\n",g);
free(q1);
return 0;
}
运行代码情况如下:
2,代码分析:
我们在用mallc申请了存储空间后所返回的指针在之后的操作中使所返回的指针的指向发生了变化,所以我们需要保存指针的指向,这里我的解决方法是对指针进行一份拷贝,而后将拷贝返回给原指针。
int main()
还没有评论,来说两句吧...