C++ _get_pgmptr函数会导致崩溃

C++ _get_pgmptr function makes crash

本文关键字:崩溃 函数 get pgmptr C++      更新时间:2023-10-16

让我参考这个https://msdn.microsoft.com/library/24awhcba(v=vs.100).aspx#Anchor_1

他们说

如果成功,则返回零;失败时返回错误代码。如果 pValue 为 NULL,调用无效的参数处理程序,如中所述 参数验证。如果允许继续执行,则此 函数将 errno 设置为 EINVAL 并返回 EINVAL。

但是我的程序只是死了,而不是返回错误。有没有人知道如何使程序返回错误?

代码

#include <stdlib.h>
char* pPath;
if( _get_pgmptr(&pPath) != 0 )
    return false;

除非我从您的帖子中遗漏了某些内容,否则这是可以更改的 CRT 安全功能。从 MSDN:

大多数安全性增强型 CRT 函数和许多预先存在的函数都会验证其参数。这可能包括检查指针中的 NULL、检查整数是否落入有效范围或检查枚举值是否有效。找到无效参数时,将执行无效的参数处理程序。

默认的无效参数调用 Watson 崩溃报告,这会导致应用程序崩溃,并询问用户是否要将故障转储加载到Microsoft进行分析。

如果要在此之后允许继续而不是崩溃,解决方案是使用 _set_invalid_parameter_handler 设置无效的参数处理程序

MSDN 中的示例针对问题中的用例进行了调整:

// crt_set_invalid_parameter_handler.c
// compile with: /Zi /MTd
#include <stdio.h>
#include <stdlib.h>
#include <crtdbg.h>  // For _CrtSetReportMode
#include <errno.h>
void myInvalidParameterHandler(const wchar_t* expression,
   const wchar_t* function, 
   const wchar_t* file, 
   unsigned int line, 
   uintptr_t pReserved)
{
   // it's a good idea to keep some logging here:
   printf("Invalid parameter detected in function %s."
            L" File: %s Line: %dn", function, file, line);
   printf("Expression: %sn", expression);
   // no abort
}

int main()
{
   _invalid_parameter_handler oldHandler, newHandler;
   newHandler = myInvalidParameterHandler;
   oldHandler = _set_invalid_parameter_handler(newHandler);
   // Disable the message box for assertions.
   _CrtSetReportMode(_CRT_ASSERT, 0);
   _get_pgmptr(NULL);
   assert(EINVAL == errno());
   return 0;
}

但是,请记住,这全局适用于程序中的所有参数验证,因此这可能不是一个好主意。最好在调用函数之前检查参数,因为这将保留更安全的参数验证全局。您可以通过以下方式实现相同的errno值:

if (pOut) 
{
    _get_pgmptr(pOut);
}
else
{
    _set_errno(EINVAL);
}

看看这个。

https://developercommunity.visualstudio.com/content/problem/245223/-get-pgmptr-bad-value-after-windows-10-update-to-1.html

似乎 MS 在 Win10 更新后更改了 VC 运行时。对于我的情况,更新后,使用VS2010_get_pgmptr()就可以了。使用VS2015它崩溃..

使用 GetModuleFileName() 代替 _get_pgmptr()。