p*******n 发帖数: 273 | 1 c语言中free要和malloc或者calloc等配合使用.
如果我先a=(double *)malloc(10*sizeof(double))
然后 double *b=a+5;
free(b)会不会把a指向的内存都释放了?
一直搞不明白free是怎么知道要free的内存大小. |
T*****9 发帖数: 2484 | 2 会段错误的
【在 p*******n 的大作中提到】 : c语言中free要和malloc或者calloc等配合使用. : 如果我先a=(double *)malloc(10*sizeof(double)) : 然后 double *b=a+5; : free(b)会不会把a指向的内存都释放了? : 一直搞不明白free是怎么知道要free的内存大小.
|
p*******n 发帖数: 273 | 3 多谢. 发现free()之后还可以对原来的内存访问,free的作用到底是什么?
#include
#include
char *mkarray()
{
char *a;
a=(char *)malloc(4*sizeof(char));
a[0]='a';a[1]='r';a[2]='e';a[3]='y';
return (a);
}
int main()
{
char *b,*c;
b=mkarray();
c=b+2;
free(b);
printf("%c %c %c %c\n",b[0],b[1],b[2],b[3]);
printf("%c %c \n",c[0],c[1]);
return 0;
}
输出结果是
a r e y
e y
【在 T*****9 的大作中提到】 : 会段错误的
|
h*******e 发帖数: 225 | 4 the heap allocator records the size of the memory block so that you dont
need to specify the size when freeing it. you can read more about the heap
management.
【在 p*******n 的大作中提到】 : c语言中free要和malloc或者calloc等配合使用. : 如果我先a=(double *)malloc(10*sizeof(double)) : 然后 double *b=a+5; : free(b)会不会把a指向的内存都释放了? : 一直搞不明白free是怎么知道要free的内存大小.
|
h*******e 发帖数: 225 | 5 behavior undefined if you access it after freeing. likely to crash if you do
other malloc/free.
【在 p*******n 的大作中提到】 : 多谢. 发现free()之后还可以对原来的内存访问,free的作用到底是什么? : #include : #include : char *mkarray() : { : char *a; : a=(char *)malloc(4*sizeof(char)); : a[0]='a';a[1]='r';a[2]='e';a[3]='y'; : return (a); : }
|
p*******n 发帖数: 273 | 6 Thanks a lot.
do
【在 h*******e 的大作中提到】 : behavior undefined if you access it after freeing. likely to crash if you do : other malloc/free.
|
T*****9 发帖数: 2484 | 7 free之后要对free的指针清NULL
【在 p*******n 的大作中提到】 : 多谢. 发现free()之后还可以对原来的内存访问,free的作用到底是什么? : #include : #include : char *mkarray() : { : char *a; : a=(char *)malloc(4*sizeof(char)); : a[0]='a';a[1]='r';a[2]='e';a[3]='y'; : return (a); : }
|
x****u 发帖数: 44466 | 8 看一下数据结构里面动态内存分配一节就明白了。
free后内存可以访问不是必然发生的。
【在 p*******n 的大作中提到】 : 多谢. 发现free()之后还可以对原来的内存访问,free的作用到底是什么? : #include : #include : char *mkarray() : { : char *a; : a=(char *)malloc(4*sizeof(char)); : a[0]='a';a[1]='r';a[2]='e';a[3]='y'; : return (a); : }
|