wattbatt
wattbatt

Reputation: 477

Is it safe to cast a pointer as an int to return from an int function in C?

I'm managing a linked list and I use a int checker(...) function to return 1 if an element is found or 0 otherwise. I also have to delete elements, so while I'm checking I would like to get the address of a certain found element if it has to be deleted.

My idea is to put a "delete mode" if(..) that makes checker return the element's address instead of return 1; and then use it to free the space.

Now my question is, am I going toward big problems writing return (int)pointeraddress in the function checker and then recasting it like this outside? I never tried doing a cast like this.

someint=checker(..);
free((pointertype)someint);```

Maybe it is safer to use long int for checker? I can't use uintptr_t as suggested in other questions because for this task I'm required to use only standard C library.

Upvotes: 2

Views: 107

Answers (1)

chux
chux

Reputation: 153498

Is it safe to cast a pointer as an int to return from an int function in C?

The cast to int itself is not a problem, but info may be lost for the next steps.

An int is not certain to round-trip back to an equivalent pointer.

An int may lack enough bits to store all needed info about the pointer.

someint=checker(..);
free((pointertype)someint); // bad

C provides optional integer types (u)intptr_t in standard C library.

I can't use uintptr_t as suggested in other questions because for this task I'm required to use only standard C library.

This is curious as uintptr_t ubiquitously exists in all standard C library since C99. @Thomas Jager

These types are wide enough to convert an object_pointertype --> (u)intptr_t --> object_pointertype successfully - results in a pointer that equates to the original.

#include <stdint.h>

Maybe it is safer to use long int for checker?

Perhaps, yet not really. long may still be too narrow.

long long may be too narrow also, yet that is less likely.


Converting to an integer type may be the wrong approach

Instead of "return 1 if an element is found or 0 otherwise.", consider
"return the address if an element is found or NULL otherwise."

or something like the below and store the found pointer in *destination,

bool find(void **destination, input parameters );

checker() needs to indicate 2 things

From a design standpoint, the found pointer, when converted to an integer, may be any value, even 0 or 1. A robust design would simply indicate 2 independent things: pointer found, value of that pointer. To roll those together implies some pointer is special and can never be "found". A generic linked list would support storing and retrieving all pointers, including null pointers.

Upvotes: 2

Related Questions