超出范围后数组未释放

Array isn't free'd after going out of scope

我有一个用于从管道读取的简单字符数组。 这个数组在无限while循环中使用

int main() 
{   
    mkfifo("process1_write", 0666); 
    mkfifo("process1_read", 0666); 
    int fd1,fd2;  
    fd1 = open(process1_write, O_RDWR);
    fd2 = open(process1_read, O_RDONLY| O_NONBLOCK);  
    std::string outmsg  = "{process: drv_rtnode_1, message: hi}";
    while (1) 
    { 
        char str1[1050];
        printf("cycle %d\n\t",i++);
        int in = read(fd2, str1, 1024);
        if(in>0)
        {
            printf("message: %s, in: %d\n", str1, in); 
            write(fd1, outmsg.c_str(), outmsg.size());
        }
        else
            printf("No content received\n");
        sleep(1);
    } 
    return 0; 
} 

如您所见,str1 在堆栈上作为局部变量实例化,因此我希望它在每个 while 循环后被释放。

但是我得到的是以下内容:

循环1:从PIPE接收数据,进入if(in>0)

message: {"msg type": "status inst", "ProcessName": "process1", "StatusDetail": "dettaglio componente"}{"msg type": "status ses", "ProcessName": "process1", "GroupName": "MOT", "GroupSts": "Online", "ActiveSession": "PRI", "StatusDetail": "dettaglio sessione"}, in: 251

in = 251,所以它计算的字符数是正确的

周期 2:从 PIPE 接收 LESS 数据

这次我收到这条消息:{"state":"alive"} 但这是打印输出:

message: {"state":"alive"}tus inst", "ProcessName": "process1", "StatusDetail": "dettaglio componente"}{"msg type": "status ses", "ProcessName": "process1", "GroupName": "MOT", "GroupSts": "Online", "ActiveSession": "PRI", "StatusDetail": "dettaglio sessione"} , in: 17

in = 17,所以字符数再次正确计数,但我的数组根本没有清空

无论我收到什么样的数据,都会发生这种情况。

我也试过修改代码如下:

   char* str1 = new char[1050];
    while (1) 
    { 
        printf("cycle %d\n\t",i++);
        int in = read(fd2, str1, 1024);
        if(in>0)
        {
            printf("message: %s, in: %d\n", str1, in); 
            write(fd1, outmsg.c_str(), outmsg.size());
        }
        else
            printf("No content received\n");
        sleep(1);
        delete[] str1;
        str1 = new char[1050];
    } 

但一切都没有改变。它的行为完全相同。

以下:

while (1) 
{ 
    char str1[1050];

在函数调用堆栈上分配,但它是这样的:

char str1[1050];
while (1) 
{ 

因此该位置被重用,并且只分配了大约 1050 个字节。

问题是,对于字符串,需要一个 nul 终止符:

   int in = read(fd2, str1, 1024);
   if (in > 0)
   {
       str1[in] = '[=12=]';

现在用较短的数据覆盖不会显示先前的读取。