2

I wrote a basic "Hello World" program in C:

#include <stdio.h>

int main()
{
        printf("Hello World!\n");
        return 0;
}

Then, I compiled it in MSVC from the command-line as such:

cl hello.c /Fd:hello.pdb /Zi /MD /link /NODEFAULTLIB:LIBCMT.LIB

The command line arguments basically say "generate a PDB file and link with MSVCRT.LIB rather than LIBCMT.LIB".

Then, I disassembled the program and looked at the various boilerplate/CRT functions and found this in the disassembly, which was curious:

__matherr:
  00401550: 33 C0              xor         eax,eax
  00401552: C3                 ret

This is basically a function that always returns 0 in EAX whenever it's called. According to the documentation of this function, it returns 0 when there is a math error and non-0 when there isn't an error.

Does anyone have an answer as to why this function, which is supposed to return 0 in the case of a math error, is included in the executable and is hard-coded to always return 0?

nwellnhof
  • 32,319
  • 7
  • 89
  • 113
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
  • 1
    You have the CRT source code on your machine, look in the vc/crt/src directory. Note the comment: "The default matherr does nothing and returns 0". – Hans Passant Sep 20 '15 at 07:27

1 Answers1

1

matherr is supposed to be called from various math functions if a math exception is detected. The default implementation does nothing. On some platforms, it's possible to selectively replace C library functions with user-defined code ("function interposition" on ELF systems), so you could implement your own math error handler. AFAIK, this isn't possible with Portable Executables (PE) on Windows. I guess that matherr is part of the CRT only for compatibility reasons.

nwellnhof
  • 32,319
  • 7
  • 89
  • 113