Tibrogargan Tibrogargan - 1 month ago 10
C Question

Is there a downside to declaring a pointer used for allocated memory as const

It struck me that if I declare a chunk of memory using a const pointer, like so:

SomeType * const pointer = malloc(sizeof *pointer);


I can't accidentally "lose" the pointer, (i.e. by modifying it or overwriting it). This seems like a convenient "reminder" that the memory it's pointing to needs to be freed. Is there a downside to doing this? A number of things come to mind, perhaps due to returning the pointer from a function, or because it may be incompatible with a large number of library functions. However these seem like inconveniences rather than an actual error.

Answer

I don't get it. You still can forget to free it.

On the downside you cannot set it to 0 after you freed it to indicate that it is already freed, so you may risk in calling free twice (think of some error handling code to imagine where it can happen).

EDIT: Additionally, as @Dmitri said in the comments, declaring the pointer const prevents you from reallocating it (by whatever means).