1

This is my code in CentOS6.6, but I don't know why can run normal .

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

int main()
{
  char str[10]={0};
  snprintf(str,18,"0123456789012345678");
  printf("str=%s\n",str);
   return 0;
 }

$ ./test

str=01234567890123456

Why not report the error when 18 over sizeof(str)?

I think it would be Segmentation fault, but nothing is reported. I use CentOS6.6.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Marcos
  • 111
  • 1
  • 2
  • 5
  • 1
    "I think it would be Segmentation fault" --> C does not require code to catch itself when it falls. Especially when code lies to itself `char str[10]; snprintf(str,18,...` Welcome to programming [without a net](http://sandiegofreepress.org/2016/04/working-without-a-net/). – chux - Reinstate Monica Sep 24 '16 at 14:05

2 Answers2

1

Accessing memory beyond the allocated chunk is an Undefined behavior.

Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you". But the reverse is not true i.e you can not say that you'll get a segmentation fault whenever you access an un-allocated memory.

There are systems out there that operate without memory protection, thus you cannot tell whether a piece of memory actually "belongs to you", and thus don't know whether segmentation fault will occur or not, only undefined behavior is assured.

Raman
  • 2,735
  • 1
  • 26
  • 46
1

C natively does not have any boundary checking. Access out of bound memory is undefined behavior. It can cause run-time error (in form of segmentation fault) or simply overwrite some other memory area (corrupting some other variable/memory location) and run fine. IT's simply undefined.

That said, the purpose of having (using) snprintf() is to supply the length properly to avoid out of bound memory access over sprintf(). You should use it in proper way, something like

snprintf(str,sizeof(str),"0123456789012345678");

because, as mentioned in C11, chapter §7.21.6.5

[...] Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. [..]

which makes sense of using snprintf() over sprintf().

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 2
    I think "C natively does not have any boundary checking." is a good explain to why it don't report error. – Marcos Sep 24 '16 at 12:11