gpt4 book ai didi

c - C 中的内存管理(分配)

转载 作者:行者123 更新时间:2023-11-30 20:48:20 24 4
gpt4 key购买 nike

我用C(不是C++)编写了一个cmd提示符,该程序已编译,但是当我运行它时,我输入了几次命令,程序出现错误并中止我认为这是由于内存分配造成的:这是源代码:

#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;
}

最佳答案

你所在的地方:

buffer = (char*)malloc(n_buffersize + 1);
ZeroMemory(buffer,sizeof(buffer));

请注意,最初,n_buffersize = 0,因此您仅分配 1 个字节。但随后您将 sizeof(char*) 字节数清零(在 32 位系统上为 4 个字节,在 64 位系统上为 8 个字节)。

您可以将分配的字节数清零,即n_buffersize + 1。或者使用 calloc() 而不是 malloc()

关于c - C 中的内存管理(分配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42707258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com