1
int number;

// In some process

wait(&number);

Im doing a wait call on a process and want to know if this is safe or will I get undefined behavior?.

yano
  • 4,827
  • 2
  • 23
  • 35

2 Answers2

1

If by wait you mean the syscall wait that waits for a forked process to exit, then this is safe to do so. number can be uninitialized because wait will store the status in that variable.

If you are talking about another wait function, then I cannot tell you without looking at the source code of that wait function.

Pablo
  • 13,271
  • 4
  • 39
  • 59
1

This is safe because you're passing the address of a variable to a function. While number was not initialized, its address has a well defined value. So the function can safely take that address, dereference it, and write a value there, which is exactly what wait does.

The man page for wait states:

pid_t wait(int *status);

...

If status is not NULL, wait() and waitpid() store status information in the int to which it points.

You would only have undefined behavior if you attempted to read the value of number before it is written to, and only if the stored value is a trap representation (i.e. doesn't represent a "real" value).

dbush
  • 205,898
  • 23
  • 218
  • 273