Behavior of char pointer

60 views Asked by At

I am really confused about the following:

char *list = malloc(sizeof(char));

list[0] = 'a';
list[1] = 'b';
printf("%s\n", list);

My expectation was some kind of undefined behavior, because list has only memory for 1 char "object".

But the actual output is ab. Why can I access list[1] when list only has allocated memory for one char?

1

There are 1 answers

5
Sourav Ghosh On BEST ANSWER

As per your memory allocation of sizeof(char) bytes (and considering the allocation is success),

  list[1] = 'b';

is out-of-bound access, which invokes undefined behavior. There can be no expectation from a program causing UB. It can do anything, absolutely anything.

That said,

  • sizeof(char) is defined (guranteed) to be 1 in C standard.
  • Check for the success of malloc() before using the return value. Otherwise, the first access, list[0] itself will invoke UB as you'll end up dereferencing an invalid pointer (i.e., accessing invalid memory)
  • Passing a pointer to a non-null-terminated char array as argument to %s also invokes UB.