Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does this code corrupt memory?
    primarykey
    data
    text
    <p>This is a fairly newbie question which should be answerable reasonably quickly...</p> <p>Basically, after the first call to <em>Printf</em> in <em>echo</em>, the contents of <em>args</em> is corrupted. It sounds to me like i'm passing the pointers around incorrectly. But can't figure out why?</p> <pre><code>#define MAX_PRINT_OUTPUT 4096 void Echo(char *args[MAX_COMMAND_ARGUMENTS], int argCount) { for (int i = 1; i &lt; argCount; ++i) { Printf("%s ", args[i]); Printf("\n"); } }; void Printf(const char *output, ...) { va_list args; char formattedOutput[MAX_PRINT_OUTPUT]; va_start(args, output); vsnprintf(formattedOutput, sizeof(formattedOutput), output, args); va_end(args); g_PlatformDevice-&gt;Print(formattedOutput); }; void RiseWindows::Print(const char *output) { //Corruption appears to occur as soon as this function is entered #define CONSOLE_OUTPUT_SIZE 32767 char buffer[CONSOLE_OUTPUT_SIZE]; char *pBuffer = buffer; const char *pOutput = output; int i = 0; while (pOutput[i] &amp;&amp; ((pBuffer - buffer) &lt; sizeof(buffer) - 1)) { if (pOutput[i] == '\n' &amp;&amp; pOutput[i+1] == '\r' ) { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; ++i; } else if (pOutput[i] == '\r') { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; } else if (pOutput[i] == '\n') { pBuffer[0] = '\r'; pBuffer[1] = '\n'; pBuffer += 2; } else { *pBuffer = pOutput[i]; ++pBuffer; } ++i; } *pBuffer = 0; SendMessage(this-&gt;ConsoleWindow.hwndBuffer, EM_LINESCROLL, 0, 0xffff); SendMessage(this-&gt;ConsoleWindow.hwndBuffer, EM_SCROLLCARET, 0, 0); SendMessage(this-&gt;ConsoleWindow.hwndBuffer, EM_REPLACESEL, 0, (LPARAM)buffer); }; </code></pre> <p><strong>NOTE</strong> This is not production code, just proof of concept.<br> <strong>EDIT</strong> g_PlatformDevice is of type RiseWindows, if that wasn't clear...<br> <strong>EDIT</strong> This is on a windows xp platform running under vs2008 </p> <p><strong>UPDATE</strong> For anyone interested, the problem appears to have been an overflowed call stack, further down the stack then this another large array was being defined. Refactoring this eliminated the memory corruption. So chalked up to stack battering!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload