#include <stdio.h>
#include <malloc.h>
int main()
{
int* p1 = (int*)malloc(40);
int* p2 = (int*)1234567;
int i = 0;
for(i=0; i<40; i++)
{
*(p1 + i) = 40 - i;
}
free(p1);
for(i=0; i<40; i++)
{
p1[i] = p2[i];
}
return 0;
}
以上代码存在很多问题如下表示:
#include <stdio.h>
#include <malloc.h>
for(i=0; i<40; i++)
{
*(p1 + i) = 40 - i; //操作的是对P1指向的往后的40个整形空间初始化,而前面动态分配的空间只有40个字节,因此出现问题。
}
free(p1); //虽然这里释放了指针,但是p1没有指向NULL,而是指向了一个地址,所以p1在这里是野指针。
for(i=0; i<40; i++)
{
p1[i] = p2[i];//将野指针地址的数据赋值给另一个错误的指针,明显错误。
}
return 0;
}
修改如下:
#include <stdio.h>
#include <malloc.h>
int array[50] = {1,2,3,4,5,6,7};
int main()
{
int* p1 = (int*)malloc(40sizeof(int));
int p2 = array;
int i = 0;
for(i=0; i<40; i++)
{
*(p1 + i) = 40 - i;
}
printf("p1 = %p.\n",p1);
printf("p2 = %p.\n",p2);
for(i=0; i<40; i++)
{
p1[i] = p2[i];
}
printf("p1 = %p.\n",p1);
printf("p2 = %p.\n",p2);
free(p1);
p1 = NULL;
return 0;
}
/练习代码
#include <stdio.h>
#include <string.h>
#include <malloc.h>
char wd_name[] = “hello word!”;
struct Student
{
char name ;
int number;
};
void del(char p)
{
printf("%s\n", p);
free(p);
}
int main()
{
struct Student s ;
struct Student * s_tp = (struct Student*)malloc(sizeof(struct Student));
s_tp->name = “hellosssssssssssssssssssssssssssssssssssssssssssss”;
s_tp->number = 99;
printf("%s %d.\n",s_tp->name,s_tp->number);
free(s_tp);
return 0;
}
free;free()是C语言中申请内存空间与释放内存空间的函数
只释指向堆空间的指针,指向其他的区域的指针他不释放
因篇幅问题不能全部显示,请点此查看更多更全内容