简体   繁体   中英

Static variables in C not initialized to zero

I am working on a large C project for a company.

I have realized that some times in the compiled executable, static variables used in C files are not initialized to zero and have some value in them. But when I edit the code a bit, like adding a print statement any where in the project, the issue is resolved.

I am using a Broadcom STB mips cross-compiler toolchain for compiling the codes.

The program is run on a Broadcom 97241 chipset running Linux 3.1.3.

[EDIT] I tried a clean build also but the problem did not go away.

The C standard requires that static variables must be initialized at the start of the program. If you don't initialize them, then the compiler will initialize them to 0. So if you are using normal compiler, then all your static variables are initialized to 0 if you don't initialize them explicitly. Such problems may occur if:

1) Some of your code set the value to a static variable.

2) The compiler is not C compiler.

3) Your program damage the memory and then you can't rely on assertions, on printf() , etc

Anyway. Try to initialize static variables to 0 explicitly. (to cut the 2 point off). And hope there is a way to debug your application. Debugger is much more useful in such problems, then asking such abstract question here.

As already has been stated, the static variables are set to 0 by the compiler. If you see some different behaviour it is most likley your code corrupting it somewhere (ie array overrun or similar).

In order to track this problem you should set a breakpoint on main and verify that the variables are indeed 0. If not, it would be a compiler bug.

If the variable is 0 then set a memory access breakpoint on it and you should see where you are corrupting it.

Without seeing the code it's really not helpfull to ask here, as any answer is just guessing, so we can only provide generic answers.

Variables declared as static should be initialised to 0, because the bss should be initialised to 0 on startup.

Adding printf statements and having the problem go away sounds like it could be a memory corruption issue. Are you accessing an array out of bounds, overflowing the stack, etc?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM