C 中指针上的自由函数如何工作?
How does free function on pointer in C work?
看看这段 C 代码:
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr_one;
ptr_one = (int *)malloc(sizeof(int));
if (ptr_one == 0){
printf("ERROR: Out of memory\n");
return 1;
}
*ptr_one = 25;
printf("%d\n", *ptr_one);
free(ptr_one);
printf("%d\n", *ptr_one);
return 0;
}
当我运行这段代码时,它给出了这个输出:
25
25
即使我释放了指针,为什么它仍然给出 25 作为输出?
阅读更多关于 undefined behavior (UB) 的内容。您的代码有一些(在 free
-d 之后,您不允许对指针执行某些操作)。
Even after I free the pointer, why is it still giving 25 as output?
是UB。你运气不好。成为 .
阅读C11标准规范n1570。
您真的不需要了解 free
的工作原理(但您需要了解应该如何使用它)。但是,它通常使用一些 operating system specific system call dealing with virtual address space. On Linux, many C standard library implementations -e.g. GNU glibc or musl-libc - are free software (so you can download and study their source code), and their malloc
might sometimes get more virtual address space with system calls like mmap(2) (or the old sbrk(2)), and their free
might sometimes release some space with munmap(2).
通常发生的情况是 C dynamic memory allocation 对 "large" 和 "small" 内存区域的工作方式不同。对于小区域,C 库更愿意在将来 malloc
-s 中重用以前的 free
-d 个。它(有时)从 OS 获取一大块内存(使用 mmap
)并将该块分成几块。当您 free
一个小区域时,该区域会简单地添加到一些片段集合中,以供将来 malloc
使用。所以它仍然 "exists" 但使用它是 UB(这解释了你观察到的行为)。
valgrind 实用程序是寻找内存相关 UB 的非常有用的工具。
当您使用 free
时唯一发生的事情是您告诉操作系统(或类似系统)您保证不会再次使用该指针。函数free
接受一个指针作为参数,而不是指向指针的指针,因此不能改变指针。
看看这段 C 代码:
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr_one;
ptr_one = (int *)malloc(sizeof(int));
if (ptr_one == 0){
printf("ERROR: Out of memory\n");
return 1;
}
*ptr_one = 25;
printf("%d\n", *ptr_one);
free(ptr_one);
printf("%d\n", *ptr_one);
return 0;
}
当我运行这段代码时,它给出了这个输出:
25
25
即使我释放了指针,为什么它仍然给出 25 作为输出?
阅读更多关于 undefined behavior (UB) 的内容。您的代码有一些(在 free
-d 之后,您不允许对指针执行某些操作)。
Even after I free the pointer, why is it still giving 25 as output?
是UB。你运气不好。成为
阅读C11标准规范n1570。
您真的不需要了解 free
的工作原理(但您需要了解应该如何使用它)。但是,它通常使用一些 operating system specific system call dealing with virtual address space. On Linux, many C standard library implementations -e.g. GNU glibc or musl-libc - are free software (so you can download and study their source code), and their malloc
might sometimes get more virtual address space with system calls like mmap(2) (or the old sbrk(2)), and their free
might sometimes release some space with munmap(2).
通常发生的情况是 C dynamic memory allocation 对 "large" 和 "small" 内存区域的工作方式不同。对于小区域,C 库更愿意在将来 malloc
-s 中重用以前的 free
-d 个。它(有时)从 OS 获取一大块内存(使用 mmap
)并将该块分成几块。当您 free
一个小区域时,该区域会简单地添加到一些片段集合中,以供将来 malloc
使用。所以它仍然 "exists" 但使用它是 UB(这解释了你观察到的行为)。
valgrind 实用程序是寻找内存相关 UB 的非常有用的工具。
当您使用 free
时唯一发生的事情是您告诉操作系统(或类似系统)您保证不会再次使用该指针。函数free
接受一个指针作为参数,而不是指向指针的指针,因此不能改变指针。