1 year ago

#240066

test-img

chux - Reinstate Monica

Proper end pointer with strtol() and "0x"?

strtol("0x", &endptr, 16);

This completes with endptr pointing to "0x". I expected "x". Is my C library's strtol() amiss, my expectations or something else?

The "0x" appears to be the beginning of an optional "0x" prefix, yet since it is not followed by a hex-digit, I would expect it to not qualify as a prefix and the parsed value should be from "0" with a non-numeric trailing "x". As is, strtol() implies no conversion since the end pointer points to the string beginning.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  char *endptr = "None";
  long val;

  errno = 0;
  val = strtol("0q", &endptr, 16);
  printf("val:%ld, errno:%d, endptr:<%s>\n", val, errno, endptr);

  errno = 0;
  val = strtol("0x", &endptr, 16);
  printf("val:%ld, errno:%d, endptr:<%s>\n", val, errno, endptr);

  return 0;
}

Output:

val:0, errno:0, endptr:<q>
val:0, errno:0, endptr:<0x>  (Expected <x>)

C spec (emphasis mine):

... If the value of base is 16, the characters 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present. C17dr § 7.22.1.4 3

The subject sequence is defined as the longest initial subsequence of the input string, starting with the first non-white-space character, that is of the expected form. The subject sequence contains no characters if the input string is empty or consists entirely of white space, or if the first non-whitespace character is other than a sign or a permissible letter or digit. C17dr § 7.22.1.4 4

Select build output info:

Invoking: Cygwin C Compiler
gcc -std=c11 -O0 -g3 -pedantic -Wall -Wextra -Wconversion -c -fmessage-length=0 -v -MMD -MP -MF"Day1.d" -MT"Day1.d" -o "Day1.o" "../Day1.c"
Target: x86_64-pc-cygwin
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.2.0 (GCC) 
COLLECT_GCC_OPTIONS='-std=c11' '-O0' '-g3' '-Wpedantic' '-Wall' '-Wextra' '-Wconversion' '-c' '-fmessage-length=0' '-v' '-MMD' '-MP' '-MF' 'Day1.d' '-MT' 'Day1.d' '-o' 'Day1.o' '-mtune=generic' '-march=x86-64'
 /usr/lib/gcc/x86_64-pc-cygwin/11/cc1.exe -quiet -v -MMD Day1.d -MF Day1.d -MP -MT Day1.d -dD -idirafter /usr/lib/gcc/x86_64-pc-cygwin/11/../../../../lib/../include/w32api -idirafter /usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/lib/../lib/../../include/w32api ../Day1.c -quiet -dumpbase Day1.c -dumpbase-ext .c -mtune=generic -march=x86-64 -g3 -O0 -Wpedantic -Wall -Wextra -Wconversion -std=c11 -version -fmessage-length=0 -o /cygdrive/c/Users/TPC/AppData/Local/Temp/ccoGk5b2.s
GNU C11 (GCC) version 11.2.0 (x86_64-pc-cygwin)
    compiled by GNU C version 11.2.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP

c

language-lawyer

strtol

0 Answers

Your Answer

Accepted video resources