1

while I am trying to understand processes I noticed something

int main(){

pid_t pid,w;

printf("value of w: %d\n", w);

return 0;

}

When I run the above code, the value of w is 0. So far no problem.

BUT

when i added char array in the code like below

int main(){

pid_t pid,w;
char arr [3];

printf("value of w: %d\n", w);

return 0;

}

The value of w is randomly changing every time I run it. I can't understand the reason for this, What is the effect of the char array?

ismet
  • 39
  • 7
  • 2
    Does this answer your question? [(Why) is using an uninitialized variable undefined behavior?](https://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior) – Piotr Siupa Aug 10 '20 at 21:55

2 Answers2

0

The value of the variable is indeterminate. When you read the indeterminate value (there are exceptions which may or might not - and typically don't - apply in this case depending on definition of pid_t), the behaviour of the program is undefined.

For some unknown reason, you've chosen to expect the behaviour to remain same when you made changes to the program. There is no guarantees for the behaviour of the program when it is undefined, and such expectation is not a reasonable assumption.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

In C and C++ variables do not get initialized automatically when you declare them. If you fail to initialize them, the state of those variables is undefined. You need to change your code to initialize your pid_t variables:

int main(){
  pid_t pid = 0;
  pid_t w = 0;
  char arr [3] = {0, 0, 0};
  
  printf("value of w: %d\n", w);
  
  return 0;

}
mmackliet
  • 272
  • 1
  • 12
  • Side note: Sometimes they do get initialized for you. Global variables, for example – user4581301 Aug 10 '20 at 21:59
  • Good point. Perhaps a better answer would be: variables in C/C++ are not always initialized for you, and you should probably just always initialize them unless you have a reason not to to avoid bugs now or bugs in the future by someone maintaining your code. – mmackliet Aug 10 '20 at 22:04