C Dynamic Allocation Why can I modify or access memory that I released with free()?

Asked 2 years ago, Updated 2 years ago, 85 views

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *pList = NULL, i = 0;

    pList = (int*)malloc(sizeof(int) * 3);

    pList[0] = 10;
    pList[1] = 20;
    pList[2] = 30;

    for(i=0; i <3; ++i) {
        printf("%d\n", pList[i]);
    }

    free(pList);

    printf('\n ********** \n');

    pList[0] = 10;
    pList[1] = 20;
    pList[2] = 30;

    for(i=0; i <3; ++i) {
        printf("%d\n", pList[i]);
    }

    return 0;
}

I have a question while studying dynamic allocation this time.

It says here that free() releases the memory that has been allocated dynamically and returns it to the operating system.

How can I modify or access the value even after releasing it?

Shouldn't there be no access to the price at all if it's been lifted?

c dynamic-allocation

2022-09-20 20:16

2 Answers

Allocate memory to malloc and release it as free.

For example, if you are assigned 10 bytes to malloc, and you are assigned 20 bytes to malloc again, the two memories do not overlap.

However, if you are allocated 10 bytes to malloc first, then release the memory to free, and then allocate the memory to malloc again, in this case, you may be allocated some or all of the memory you just released to free.

In the end, you can think of free as a role to release it so that it can be assigned as malloc again.

You can usually learn process images in subjects like the operating system. The memory to which the malloc function is assigned is the memory of the heap region in the process image.

From the question code

free(pList);
pList[0] = 10;

You can read it even though it's off, but you can even change it.

So you usually enter NULL after using free.

free(pList);
pList=NULL;

Then pList[0] = 10; will no longer work.


2022-09-20 20:16

It's expensive to mark this part of the memory as free so that it won't be accessed again.


2022-09-20 20:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.