You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何调用strerror_s传入ERROR_NOT_ENOUGH_MEMORY返回"Exec format error"?

问题:Windows下strerror_s返回错误的错误信息
#include <stdio.h>
#include <windows.h>
#include <stdlib.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;
}

运行上述代码时,调用strerror_s并传入ERROR_NOT_ENOUGH_MEMORY错误码,却返回"Exec format error"错误信息,而非预期的“Not enough memory resources are available to process this command”类提示。已查阅strerror_s及Windows系统错误码的官方文档,仍无法理解原因,特此求助。


原因及解决方案

核心原因

strerror_s是C标准库函数,仅能解析C标准定义的错误码(如errno相关取值),而ERROR_NOT_ENOUGH_MEMORY是Win32 API专属的系统错误码,两者不属于同一错误体系,直接传入必然无法得到正确描述。

正确实现方式

要获取Win32错误码对应的描述信息,需使用Windows API提供的FormatMessage函数,示例代码如下:

#include <stdio.h>
#include <windows.h>
#include <stdlib.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
    {
        DWORD msgLen = FormatMessageA(
            FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            ERROR_NOT_ENOUGH_MEMORY,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            cErrorMessage,
            SMALL_BUFFER,
            NULL
        );

        if (msgLen == 0)
        {
            fprintf(stderr, "Failed to fetch error message\n");
        }
        else
        {
            fprintf(stderr, "%s", cErrorMessage);
        }
    }

    free(cErrorMessage);
    return 0;
}

关键参数说明

  • FORMAT_MESSAGE_FROM_SYSTEM:指定从系统消息表中加载错误描述
  • FORMAT_MESSAGE_IGNORE_INSERTS:忽略错误信息中的占位符,简化处理流程
  • MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT):自动适配系统当前语言设置,返回对应语言的错误描述

内容的提问来源于stack exchange,提问作者Johnson_Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:06:25