Search code examples
cprintfbuffer-overflow

Bufferoverflow, snprintf instead char resizes?


I have a hard time to understand why the below code is not resulting in a bufferoverflow and instead some how seems to resize the char example from 1 to 16.

I checked the snprintf documentation but nothing to be found about this.

//set char example size 1
char example[1];

//set example to args->arg2 which is a 15 character + 1 null byte.
//trying to put something to big into something too small, in my mind causing not a resize but a bof.

snprintf(example, 16, "%s", args->arg2); 

fprintf(stdout,"[%s],example);

The fprintf in the end does not display 1 character nor does char example overflows but instead it seems to be resized and displays the full string of 16.

What am i misunderstanding here ?


Solution

  • Your array is not resized. Instead what happens is that there is some memory following it (in fact it's your call stack, which is why overruns like this are dangerous), and snprintf 'trusts' you and writes into that memory. fprintf after that happily reads whatever snprintf wrote there.

    It works for you now, but it is undefined behavior, which means that, sooner or later, it will break.