Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Has this C code a defined behavior?

This is a thought experiment, not production code nor good coding style.

Suppose we have this function

int find_process_pid_by_name(char* name, int* threads_in_process);

that return the PID of a named process and also always store into threads_in_process the number of threads running in said process.

A lazy programmer, interested only on the PID, writes this code

int pid = find_process_pid_by_name("a process name", &pid);

Does it trigger undefined behavior?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

No — I don't think it is undefined behaviour. There's a sequence point immediately before the function is called (after the arguments and the expression that denotes the called function have been evaluated), and there's another before the called function returns. Any side-effects on pid performed by the called function have been completed before the function finishes returning. The result of the function is then assigned to pid. There's no question of the location that is assigned to being changed by the function. I see nothing that invokes undefined behaviour.

I am assuming that the called function treats the int * argument as a write-only pointer to a single value. If it reads from a single value, we need to know that pid was previously initialized (formally; in practice, it won't matter). In the context, pid has not been initialized; the result of the function will initialize it. So, if the function reads from its pointer argument, technically, you have undefined behaviour. If the function treats the pointer as the start of a multi-element array and accesses beyond the zeroth element, there are problems. But these are issues somewhat outside the intended scope of the question/discussion.

over 4 years ago · Santiago Trujillo Report

0

Yes, I believe this code is well defined. There's a sequence point at the end of the function, before the return value is copied into the calling context. So the function will first assign to pid indirectly through threads_in_process, then it will return, and then the return value will be assigned to pid.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!