Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am working on converting many C programs from Unix to Linux and this free() syntax caught my attention:

free((char *) area );

What's the difference between this and free( area ); ?

share|improve this question

3 Answers 3

The signature of free is:

void free(void *ptr);

So if area is a pointer type that is returned by malloc or its cousins, the conversion in free((char *) area ); is pointless.

Unless... if the code is really, really old, that is, before ANSI C introduced void * as generic pointer. In that ancient time, char * is used as generic pointer.

share|improve this answer

If someone were storing a pointer to dynamic allocated data in a non-pointer type sanctioned by the standard, i.e. area is declared as intptr_t for example, this casts the non-pointer to a pointer type and allows it to be freed.

If area is already a pointer type, this makes no sense at all with any C code written in the last quarter-century.

share|improve this answer

The signature of free() in the standard is wrong. It should have been void free(const void *); to be really correct. This has the consequence that you have to upcast a const * when you want to free it without a warning.

There is a Linus Torvald rant about on why free() should take a const *.

share|improve this answer
    
I'm not convinced about that. malloc returns non-const, so for one thing you need to have a cast in between the malloc and free for this to be needed. Second, const indicates a contract that means you do not modify the contents of the memory pointed to. freeing that memory is a violation of that contract. I can't think think of any arguments for it, so I'd be interested in arguments that are pro-const. –  MicroVirus 8 hours ago
    
See yarchive.net/comp/const.html for the Linus Torvalds's rant. –  hmp 5 hours ago
    
MicroVirus, read Linus' rant, he explains it better as I ever could and he is right. –  tristopia 5 hours ago
    
@MicroVirus: Free doesn't modify the contents. It obliterates its very existence. –  Zan Lynx 2 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.