DEV
DEV

Reputation: 2176

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..?

Upvotes: 0

Views: 68

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

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++.

Upvotes: 7

Related Questions