Jack Murrow
Jack Murrow

Reputation: 426

Is typecasting long to size_t safe?

I want to use ftell to get the current position of stream, but I want to be able to typecast it to a size_t, which would be an unsigned instead. signed and unsigned are different because one is signed and the other is unsigned.

The return type of ftell is long, and that's different than size_t.

So, in this situation when using ftell, is it safe to use size_t for it instead of long?

char *s = malloc(ftell(whateverstream));

I'm going to be using ftell for dynamic memory allocation, so I was wondering if it's safe to use long instead of size_t.

Upvotes: 0

Views: 214

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126243

Depends on what you mean by "safe" -- it is always well-defined to convert a long to a size_t, but that might not do what you want.

The basic problem is that there's no mandated relationship between long and size_t -- a size_t might be smaller than a long, or larger, or the same size. It depends on the implementation (machine and compiler).

If you're using a POSIX system, there's also ftello, which returns an off_t rather than a long (which might be larger than a long, and larger or smaller than a size_t).

So to be totally safe, you need to check all the possible combinations -- check that the return value from ftell(o) is not negative, and then after converting it to a size_t, check that it didn't wrap due to overflow

long off = ftell(whatever);
size_t size = (size_t)off;
if (off < 0) {
    /* there was an error determining the size of the stream */
} else if (size != off) {
    /* overflow converting to size -- stream is too big */
} else {
    /* converted successfully */
}

Upvotes: 2

Related Questions