Should the pointer passed to free () point to the beginning of the allocated space?

Let's say I used mallocto request free space. The variable ptrindicates the created memory space. In my code, the value is ptrchanged to access various locations in the allocated space.

The call free(ptr), after it has ptrbeen changed, will not be correct, no ?. Instead, I have to create a replica ptrafter malloc. This new pointer should be used instead in a function call free. Is it correct?

Greetings

+4
source share
4 answers

free(ptr), , ptr , , ?

. .

ptr malloc. free. ?

:

  • , malloc ed. free .

  • , , malloc ed. free .

  • . malloc ed. free .

, malloc, , malloc, free.

+4

, . , C11,

7.22.3.3 free

... , , free realloc, undefined

, free - undefined , , .

+2

7.20.3.2, c99, [ ]

free , ptr, . ptr - , . , , calloc, malloc realloc, free realloc, undefined.

, free(), malloc() family. .

To do your job, you first need to make a copy of the original pointer returned malloc(), and as soon as you finish using memory, you need to call free()with the previously saved value.

+1
source

Yes. You understood correctly. When ptrmodified to indicate a different location, then the call freewill be allocated with the memory allocated malloc.
You need to keep a copy of the returned pointer.

0
source

All Articles