C中的指针的自由函数如何工作? [英] How does free function on pointer in C work?

查看:64
本文介绍了C中的指针的自由函数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这个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;
}

运行此代码时,它给出以下输出:

When I run this code, it gives this output:

25
25

即使我释放了指针,为什么它仍然给出25作为输出?

Even after I free the pointer, why is it still giving 25 as output?

推荐答案

阅读有关未定义行为的更多信息(UB).您的代码中包含一些内容(free -d后不允许使用指针做任何事情).

Read a lot more about undefined behavior (UB). Your code has some (you are not allowed to do something with a pointer after it has been free-d).

即使我释放了指针,为什么它仍然给出25作为输出?

Even after I free the pointer, why is it still giving 25 as output?

是UB.你真倒霉被吓到.

阅读C11标准规范 n1570 .

您实际上不需要了解free的工作原理(但是您需要了解如何使用它).但是,它通常使用某些操作系统特定的虚拟地址空间.在 Linux 上,许多 glibc musl-libc -是免费软件(因此您可以下载并研究其源代码),并且malloc有时有时可以通过

You don't really need to understand how free works (but you need to understand how you should use it). However, it usually uses some 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动态内存分配对于大"和小"存储区.对于小区域,C库更喜欢在将来的malloc -s中重用以前的free -d.它(有时)从OS获取大量内存(使用mmap)并将其拆分为多个部分.当您free一个小区域时,该区域会被简单地添加到一些集合中,以备将来malloc使用.因此它仍然存在",但使用的是UB(并且可以解释您正在观察的行为).

What usually happens is that C dynamic memory allocation works differently for "large" and "small" memory zones. For small zones, the C library prefer to re-use previously free-d ones in future malloc-s. It gets (sometimes) from the OS a large chunk of memory (using mmap) and split that chunk into pieces. When you free a small zone, that zone is simply added to some collection of pieces, for future malloc. So it still "exists" but using it is UB (and that explains the behavior your are observing).

valgrind 实用程序是用于搜索与内存相关的UB的非常有用的工具.

The valgrind utility is a very useful tool to hunt memory related UB.

这篇关于C中的指针的自由函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆