Dela via


C6298

warning C6298: using a read-only string <pointer> as a writable string argument: this will attempt to write into static read-only memory and cause random crashes

This warning indicates the use of a constant string as an argument to a function that might modify the contents of that string. Because the compiler allocates constant strings in a static read-only memory, any attempts to modify it cause access violations and random crashes.

This can be avoided by storing the constant string into a local array and then using the array as the argument to the function.

Example

The following sample code generates this warning:

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

void f()
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof( si ) );
    si.cb = sizeof( si );
    ZeroMemory( &pi, sizeof( pi ) );
    if( !CreateProcess(NULL,
                      "\"c:\\Windows\\system32\\calc.exe\"",
                      NULL,             
                      NULL,              
                      FALSE,            
                      0,                 
                      NULL,             
                      NULL,              
                      &si,              
                      &pi ) ) 
    {
        puts( "CreateProcess failed." );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

To correct this warning, use the following sample code:

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

void f( )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    
    char szCmdLine[] = "\"c:\\Windows\\system32\\calc.exe\"";
    ZeroMemory( &si, sizeof( si ) );
    si.cb = sizeof( si );
    ZeroMemory( &pi, sizeof( pi ) );

    if( !CreateProcess(NULL,
                      szCmdLine,
                      NULL,             
                      NULL,              
                      FALSE,            
                      0,                 
                      NULL,             
                      NULL,              
                      &si,              
                      &pi ) ) 
    {
        puts( "CreateProcess failed." );
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}