Re: Accessing void * buffer/array through char * pointer



vippstar@xxxxxxxxx writes:

On Sep 6, 2:26 pm, s0s...@xxxxxxxxx wrote:
<snip>
for (size_t i = 0; i < sizeof(hello); ++i) {
printf("byte %2zu: <%c>", i, p[i]);

Remove the 2 in %2zu, else the output might not be meaningful.

What on earth is wrong with the 2?

Evaluating p[i] can invoke undefined behavior.

I think it is better to say "may invoke undefined behaviour". I
accept that you don't agree (there's been a long thread about this
already) but just for the benefit of the OP there are systems on which
the code posted can't go wrong in any way. Using a potentially signed
char pointer merely limits the portability to a very specific class of
implementations and you, as the programmer, can know (with absolute
certainty) if the code's behaviour is defined or not beforehand. This
is quite unlike some other kinds of UB.

However, one should always used unsigned char for this purpose since
there is no advantage to be gained by using char *.

--
Ben.
.



Relevant Pages

  • Re: Hex to int
    ... char *t=s; ... int x=0, y=1; ... This loop condition is likely to invoke undefined behaviour. ...
    (comp.lang.c)
  • Re: Hex to int
    ... char *t=s; ... int x=0, y=1; ... This loop condition is likely to invoke undefined behaviour. ...
    (comp.lang.c)
  • Re: Brian Kernighan, maybe Im not worthy, maybe Im scum
    ... programmer is "free", o happy day, to use the stack copy, test itself, ... is the pointer that is being passed as the value ... static int matchhere(char *regexp, char *text) ...
    (comp.programming)
  • Re: C software achitecture
    ... > result in a buffer. ... > char** to get a char pointer back. ... > The exec function will allocate a memory buffer and the ... > programmer will need to free it afterwards... ...
    (comp.lang.c)
  • C software achitecture
    ... char** to get a char pointer back. ... The exec function will allocate a memory buffer and the ... programmer will need to free it afterwards... ...
    (comp.lang.c)