Why is this segfault

I stumbled upon something "interesting" and I tilt my finger why the behavior is not consistent.

Check out this code.

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

Simple, correct. It's easy to understand what happens when bla is a NULL pointer.

It should always be segfault right !?

On one machine, the segfaults executable, on another (my development machine), is just business, as usual.

My devel PC runs Windows7 and I am compiling with gcc/MingW . The computer on which it crashes is XP , and it has Visual studio 6 .

Why is this an accident on this computer ??

Greetings

+4
source share
6 answers

ISO C99: 7.19.6.3 The printf function

Summary

  #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**.

Thus, your code calls 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** ]

It should always be segfault right !?

Not necessarily, Undefined Behavior means that anything can happen.

+24
source

It should always be segfault right !?

Not. This causes undefined behavior. A segmentation error is one of many possible results of a UB call.

+11
source

Since printing a null reference as a string (as far as I know, not tested with standards) is undefined. Many systems simply output (null) in the result.

Same thing with other printf functions:

 printf ("%s", NULL); // Outputs (null) to the console on some systems but can crash others 
+3
source

In addition, segfault is never guaranteed. If this happens, there is an error somewhere; but with an error somewhere, segfault is not implied.

+1
source

It should always be segfault right !?

Not. It depends on the implementation of the sprintf function that comes with the standard compiler library.

As far as I know, the sprintf specification does not indicate that you should specify a non-empty address.

+1
source

It all depends on what bla points out at the time. What sprintf () will do is copy all the characters bla points to until it encounters a zero character (0x00).

If it encounters a null character before it reaches the limit buf [100], then there is no segfault, because we are not writing above the limit buf.

In addition, on some systems, if bla points to a read-only area of ​​protected memory, it can also trigger segfault as soon as the data is read.

0
source

Source: https://habr.com/ru/post/1315505/


All Articles