简体   繁体   中英

free with dynamically allocated memory

I have this C code:

int main()
{
    int *p=(int *)malloc(100);   //100 bytes

    for(int i=0;i<10;i++)
    {
        p++;
    }

    free(p);

    return 0;
}

Now my question is will free(p) free all the 100 bytes or only 90 bytes. How does free() know how many bytes to free..?

It's illegal.

The argument of free must be a pointer that is returned by malloc or its cousins, or a null pointer. In your example, p has changed its value by p++ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM