Search code examples
cwindowserror-handlingmallocstrerror

Why is strerror_s() with ERROR_NOT_ENOUGH_MEMORY error code returning "Exec format error"


Given the following example C code snippet test case;

#include <stdio.h>
#include <windows.h>

#define SMALL_BUFFER 256

int main()
{

char* cErrorMessage = malloc(sizeof(char) * SMALL_BUFFER);

if (cErrorMessage == NULL)
{
    fprintf(stderr, "Insufficient memory available\n");  
    return 1;
}
else
{
    strerror_s(cErrorMessage, SMALL_BUFFER, ERROR_NOT_ENOUGH_MEMORY);                                             
    fprintf(stderr, "%s\n", cErrorMessage);                                                                         
}

free(cErrorMessage);

return 0;
}

Why would strerror_s() with the error code ERROR_NOT_ENOUGH_MEMORY return a message of "Exec format error"?

What have I tried? I have read through the documentation for strerror_s and System Error Codes to try and figure out what is going on beneath the code.

What I was expecting? I was expecting to see an error message along the lines of "Not enough memory resources are available to process this command".


Solution

  • The macro ERROR_NOT_ENOUGH_MEMORY is a Windows-specific error code, usually returned by GetLastError(), while strerror (and strerror_s) deals with standard C error code from errno (and on POSIX systems like Linux or macOS is also the standard way to get error codes).

    To get descriptions of Windows error code you need to use FormatMessage:

    char *cErrorMessage = NULL;
    FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                   NULL,
                   ERROR_NOT_ENOUGH_MEMORY,
                   0,
                   (LPCSTR) &cErrorMessage,
                   0,
                   0);
    fprintf(stderr, "%s\n", cErrorMessage);
    LocalFree((HLOCAL) cErrorMessage);