Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this segfault

I stumbled across something "interesting" and I cant put my finger why the behaviour isn't coherent.

Check this code.

char buf[100];
sprint(buf,"%s",bla);

Simple, right. It's easy to understand what is going on when bla is a NULL pointer.

This should always segfault right!?

In one machine the executable segfaults, on another (my development machine), it's just business as usual.

My devel PC is running Windows7 and I'm compiling with gcc/MingW. The computer where this is crashing is XP and it does have Visual studio 6 installed.

Why doesn't this crash on my PC?

like image 708
André Moreira Avatar asked Nov 27 '22 23:11

André Moreira


1 Answers

ISO C99: 7.19.6.3 The printf function

Synopsis

 #include <stdio.h>
 int printf(const char * restrict format, ...);

The printf function is equivalent to fprintf with the argument stdout interposed before the arguments to printf.

7.19.6.1 The fprintf function

7.19.6.1.9

If a conversion specification is invalid, the behavior is **undefined**. If any argument is not the correct type for the corresponding conversion specification, the behavior is **undefined**.

So your code invokes Undefined Behavior [(ISO C99 3.4.3) behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes **no requirements**]

This should always segfault right!?

Not necessarily, Undefined Behavior means anything can happen.

like image 100
Prasoon Saurav Avatar answered Dec 07 '22 22:12

Prasoon Saurav