简体   繁体   中英

Using free to deallocate a non char pointer in C

While reading this article , I came across this paragraph:

Pointers to objects may have the same size but different formats. This is illustrated by the code below:

 int *p = (int *) malloc(...); ... free(p); 

This code may malfunction in architectures where int * and char * have different representations because free expects a pointer of the latter type.

And this is not the first time I read that free expects a char* type.

My question is, how to free p ?

NOTE : You should not cast the return value of malloc in C .

This question illustrates the dangers of reading potentially invalid resources. It's extremely important to ensure the resource you read is accurate! OPs resource in question, is not wrong for its era , but is well out-of-date and, consequently, is invalid . K&R 2E is ironically one year older , but is still very much in date (and thus still highly recommended) because it follows the standard.

If we consult a more reputable resource (the free manual) , we can see that free actually expects the pointer to be of void * type:

 void free(void *ptr); 

... and for what it's worth, here's the malloc manual showing that malloc returns void * :

 void *malloc(size_t size); 

In both cases, as described by C11/6.3.2.3p1 (the C11 standard):

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

int *p = malloc(...); // A conversion occurs here; `void *` as returned by malloc is converted to `int *`
free(p);              // ... and the reverse of the conversion occurs here, to complete the cycle mentioned in C11/6.3.2.3p1

NOTE (in case you missed it the first time): You should not cast the return value of malloc in C . After all, you don't need to cast it when you pass it to free , right?

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