我用C編寫了一個cmd提示符(不是C++),該程序已經編譯,但是當我運行它時,我輸入了幾次命令,程序錯誤並中止 我認爲這是應該的內存分配: 所以這是源代碼:C中的內存管理(分配)
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
char* Execute(char*);
HANDLE readIN = NULL;
HANDLE writeIN = NULL;
HANDLE readOUT = NULL;
HANDLE writeOUT = NULL;
int
main(int argc, char** argv)
{
SECURITY_ATTRIBUTES saAttr;
STARTUPINFO si;
PROCESS_INFORMATION pi;
char cmd[12];
char* out = NULL;
ZeroMemory(cmd,sizeof(cmd));
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
CreatePipe(&readOUT, &writeOUT, &saAttr, 0);
CreatePipe(&readIN, &writeIN, &saAttr, 0);
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
GetStartupInfo(&si);
si.cb = sizeof(STARTUPINFO);
si.hStdError = writeOUT;
si.hStdOutput = writeOUT;
si.hStdInput = readIN;
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
CreateProcess(NULL,
"cmd.exe",
NULL,
NULL,
TRUE,
CREATE_NEW_CONSOLE,
NULL,
NULL,
&si,
&pi
);
while (TRUE)
{
out = Execute(cmd);
printf("%s\n", out);
scanf("%s", cmd);
strcat(cmd,"\n");
}
free(out);
return 0;
}
char*
Execute(char* cmd)
{
DWORD bwritten = 0;
DWORD buffersize = 0;
int outputsize = 0;
DWORD breaden = 0;
char* output = NULL;
char* buffer = NULL;
DWORD n_buffersize;
WriteFile(writeIN, cmd, strlen(cmd), &bwritten, NULL);
while (TRUE)
{
Sleep(2000);
PeekNamedPipe(readOUT, NULL, NULL, NULL,&buffersize, NULL);
n_buffersize = buffersize;
if (n_buffersize)
{
buffer = (char*)malloc(n_buffersize + 1);
ZeroMemory(buffer,sizeof(buffer));
ReadFile(readOUT, buffer, n_buffersize, &breaden, NULL);
}
else
break;
if (breaden)
{
outputsize += n_buffersize + 1;
output = (char*)realloc(output, outputsize);
strcat(output, buffer);
free(buffer);
}
}
return output;
}
*程序錯誤並中止*是完全無用的問題說明。您發佈的代碼具有哪些**特定的問題?調試器告訴你什麼時候你通過代碼? –
調試器msg:mycmd.exe中的0x77BF62AC(ntdll.dll)的未處理異常:0xC0000374:內存段已損壞(參數:0x77C26480)。已經發生 –