Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

While compilers won't optimise functions they don't yet know about, they do know the standard library and the respective guarantees and constraints. This includes removing calls to memset for things that are never read again (horrible for passwords or keys in memory, which is why there is a SecureZeroMemory or related function in operating systems) or other things.

As a somewhat trivial example:

  #include <stdio.h>
  #include <string.h>

  int main() {
  	printf("%lu\n", strlen("Test"));
  	return 0;
  }
will get compiled by MSVC (with /O2) to

  ; Line 5
	push	4
	push	OFFSET ??_C@_04OJNJKCBM@?$CFlu?6?$AA@
	call	_printf
	add	esp, 8
  ; Line 6
	xor	eax, eax
  ; Line 7
	ret	0
The compiler knows about strlen and notices that there is no need at runtime to calculate the length of a constant string and just puts in the result.


Great example, however this does not apply to free - or I would be very surprised if it did. It is relatively common for people to override malloc and free at runtime, so I would be very surprised if the compiler treated malloc or free as a compiler intrinsic, and inlined the code. I would not be surprised, however, if the compiler used the semantics of malloc or free to reason about the surrounding code. The original point, however, was about inlined code leading to generated code that no reasonable person would write (null check after use). So I still think that would not happen for free.


I just tested clang, and free(malloc(42)); gets completely optimized out, as does free(NULL);. free(argv) doesn't, so it's not quite that clever, at least.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: