Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #163928

Re: unsafe C

From Keith Thompson <Keith.S.Thompson+u@gmail.com>
Newsgroups comp.lang.c
Subject Re: unsafe C
Date 2021-12-17 12:20 -0800
Organization None to speak of
Message-ID <87tuf76l17.fsf@nosuchdomain.example.com> (permalink)
References <d8227134-6e0b-486e-af91-aeece50a466bn@googlegroups.com>

Show all headers | View raw


Thiago Adams <thiago.adams@gmail.com> writes:
> I realized strtoull is unsafe.
>
> #include <stdlib.h>
> #include <stdio.h>
>
> int main() {
>   char* begin = "123456789011121314151617181920";
>   unsigned long long value = strtoull(begin, NULL, 10);
>   printf("%s\n", begin);
>   printf("%llu\n", value);
> }
> it prints 
> 123456789011121314151617181920
> 18446744073709551615

It's a little tricky, but it's not unsafe.

    The strtol, strtoll, strtoul, and strtoull functions return the
    converted value, if any. If no conversion could be performed, zero
    is returned. If the correct value is outside the range of
    representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX,
    ULONG_MAX, or ULLONG_MAX is returned (according to the return type
    and sign of the value, if any), and the value of the macro ERANGE is
    stored in errno.

If you set errno to 0 before calling strtoull() and check its value
after the call (before calling anything else that might set errno),
you'll find it's been set to ERANGE to indicate the error.

(18446744073709551615 is LLONG_MAX, assuming 64 bits.)

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
Working, but not speaking, for Philips
void Void(void) { Void(); } /* The recursive call of the void */

Back to comp.lang.c | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

unsafe C Thiago Adams <thiago.adams@gmail.com> - 2021-12-17 12:13 -0800
  Re: unsafe C Thiago Adams <thiago.adams@gmail.com> - 2021-12-17 12:16 -0800
    Re: unsafe C Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2021-12-17 12:25 -0800
    Re: unsafe C Meredith Montgomery <mmontgomery@levado.to> - 2021-12-18 12:40 -0300
      Re: unsafe C Meredith Montgomery <mmontgomery@levado.to> - 2021-12-25 21:41 -0300
        Re: unsafe C Meredith Montgomery <mmontgomery@levado.to> - 2021-12-25 21:42 -0300
    Re: unsafe C Andrey Tarasevich <andreytarasevich@hotmail.com> - 2021-12-18 12:29 -0800
  Re: unsafe C Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2021-12-17 12:20 -0800
    Re: unsafe C Thiago Adams <thiago.adams@gmail.com> - 2021-12-17 12:29 -0800
    Re: unsafe C Peter 'Shaggy' Haywood <phaywood@alphalink.com.au> - 2021-12-19 17:16 +1100
      Re: unsafe C Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2021-12-19 13:32 -0800
  Re: unsafe C Ben Bacarisse <ben.usenet@bsb.me.uk> - 2021-12-17 20:30 +0000
    Re: unsafe C Thiago Adams <thiago.adams@gmail.com> - 2021-12-17 12:35 -0800

csiph-web