[In a hurry] [C language] I wonder why the next function is safe!

Asked 2 years ago, Updated 2 years ago, 32 views

My professor said that the function f4 in the lower right corner of the picture here is the word warning in the compiler I will, but they said it's a safe code. In my opinion, since the f4 function is removed from the stack after the call, those functions that return the address value of the parameter refer to the undefined address value, so it will be very problematic

If you know the reason why that code is safe, please reply!

c

2022-09-22 20:37

1 Answers

Well, I think it's an unsafe code. In some cases, problems may not occur (inline). However, it is not safe because it does not guarantee that problems will not occur.

If you compile the code you uploaded from GCC 7.2 to x86-64 you will get the following results. (https://godbolt.org/g/t8f2wr)

f4(int, int):
  push rbp
  mov rbp, rsp
  mov DWORD PTR [rbp-4], edi
  mov DWORD PTR [rbp-8], esi
  mov edx, DWORD PTR [rbp-4]
  mov eax, DWORD PTR [rbp-8]
  cmp edx, eax
  jle .L2
  mov eax, 0
  jmp .L3
.L2:
  mov eax, 0
.L3:
  pop rbp
  ret

Here's what you need to look at carefully:

  cmp edx, eax
  jle .L2
  mov eax, 0
  jmp .L3
.L2
  mov eax, 0

Compare edx and eax (the value of the calling factor is stored) and jump to .L2 or .L3 according to the result, and perform move eax, 0 regardless of whether the condition is true or false.

This command stores the 0 value in the eax register, where eax is the register to pass the return value of the function.

In other words, the f4 function will unconditionally return 0 as a result of the assembly, which will act differently than you intended.

This is an unsafe function because the author of the function has different intentions and actual behavior.

So why did the professor say that the compiler was a warning, but a safe function?

One of the reasons is the optimization of the compiler.

In some cases, functions such as f4 above will become inline. If it becomes an inline function, it will not be called, but will be pasted exactly where it was called. In this case, a and b can be variables used as call factors, not new variables created in the stack. The return address can then indicate a valid address at the end of the function.

However, this may or may not be possible for each compiler. Even if it is inline, the action may or may not operate intentionally.

This is called undefined behavior and is not safe.


2022-09-22 20:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.