Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this va_start crash?

Tags:

c++

Why do two pointers pointing to the same memory have different effects in va_start, one is okay but the other crashes?

The testing environment is Visual Studio 2019.

#include <Windows.h>
#include <tchar.h>
#include <atlstr.h>

void output_ok(int iIndex, const TCHAR* szFormat, ...)
{
    TCHAR pBuf[256] = { 0 };
    va_list pArgs;
    va_start(pArgs, szFormat);
    _vstprintf(pBuf, szFormat, pArgs);
    va_end(pArgs);
}

void output_crash(int iIndex, const TCHAR* szFormat, ...)
{
    const TCHAR* fmt = szFormat;

    TCHAR pBuf[256] = { 0 };
    va_list pArgs;
    va_start(pArgs, fmt);
    _vstprintf(pBuf, fmt, pArgs);
    va_end(pArgs);
}

int main()
{
    CString OpenGLVersion("4.6.0");
    // output_ok(0, _T("OpenGL:%s"), OpenGLVersion);
    output_crash(0, _T("OpenGL:%s"), OpenGLVersion);
}
like image 937
ysouyno Avatar asked Oct 31 '25 02:10

ysouyno


1 Answers

Why do two pointers pointing to the same memory have different effects in va_start, one is okay but the other crashes?

Because the second case violates the manual requirements.

prev_param
Parameter that precedes the first optional argument.

<...> The argument prev_param is the name of the required parameter that immediately precedes the first optional argument in the argument list. <...>

Is fmt a parameter? No. This is a local variable. Is fmt the name of a function parameter? No.

like image 74
273K Avatar answered Nov 02 '25 17:11

273K