Free() function in C language

Asked 2 years ago, Updated 2 years ago, 45 views

Use malloc() and free() when dynamically allocating memory in C language.

One question is, how does the free function know the memory size dynamically allocated using malloc and solve the dynamic allocation?

#include <stdlib.h>
#include <iostream>
int main(){
    using namespace std;

    void* p;
    p = malloc(16);
    cout << p << "\n";
    cout << p+16 << "\n"

    free(p);
    cout << p << "\n";
    cout << p+16 << "\n"

}

Is the size of the dynamically allocated memory stored anywhere?

How do you protect dynamically allocated memory in the first place, and how does the free function unprotect the protected memory?

I'd appreciate it if you could let me know.

c c++

2022-09-22 19:29

1 Answers

Allocating memory to malloc (16) allocates 16 bytes of space to the user. This 16-byte means the amount of free virtual memory available to the user The memory managed by the actual operating system adds additional space for managing this memory space. The free function can read the information stored in this part of the management memory and free up the memory.


2022-09-22 19:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.