user4954224
user4954224

Reputation:

Is calling atoi without stdlib undefined behaviour?

Is calling atoi without including stdlib.h undefined behaviour? I can't find where I have included stdlib.h in my project, even though I have used atoi. The thing is actually atoi has been working fine - it has been parsing integers correctly every time the software has been used. It is some embedded device. So is there case this can be well defined?


btw. In this line:

#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
#include "sdkGlob.h"


#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */

that header includes stdlib.h but I can't understand in which case it is included. And I am not sure if this cplusplus is defined anywhere. This is a c project anyway.

Upvotes: 2

Views: 201

Answers (2)

JPC
JPC

Reputation: 274

The short answer

Two possibilities:

  • It's probable that sdkGlob.h include stdlib.h or define its own version of atoi.
  • Some compilers, like GCC, resolve missing #include and even hide the errors or warnings. Run gcc -Wall and check if warnings appears.

About ifndef

The #ifdef __cplusplus sections are used by C++ compilers. Here, you're saying '*if and if only the code is being compiled by a C++ compiler, do ... *'.

The C-only version of your code:

#include "sdkGlob.h"

The C++-only version of your code:

extern "C"{
  #include "sdkGlob.h"
}

Upvotes: 2

Tommy
Tommy

Reputation: 100652

Prior to C99 it was acceptable to use functions that hadn't previously been declared. The compiler might generate a warning but there would be no error until the linker either didn't find the function or found a function of the same name with a signature other than the one that the compiler had guessed. Luckily for you, the compiler always guesses a return type of int.

In C99 it became necessary for function declarations to be visible but not all compilers strictly enforce the rule.

As per Random832's comment, it's also quite possible that sdkGlob simply includes stdlib for itself.

As to your other question: sdkGlob is always included but if run through a C++ compiler rather than a C compiler you also get the extern "C"{ .. } wrapping. That tells the C++ compiler not to mangle the names so that you can link against a version of that module that was built using an ordinary C compiler. It's the normal way to provide plain C libraries in a way that allows them to be used by both C and C++ code.

Upvotes: 3

Related Questions