C中子进程kill掉后为什么会泄漏内存?

问题描述 投票:0回答:1

我需要在 (if) 块的末尾终止子进程。但是杀死它会导致内存泄漏 在 ubuntu 终端上试过。

compile:  gcc -W -Wall -Wextra mallocFork.c

运行:valgrind ./a.out

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

int main()
{
    int *numbers = (int *)malloc(sizeof(int) * 3);
    numbers[0] = 1;
    numbers[1] = 2;
    numbers[2] = 4;
    int child = fork();
    for (int i = 0; i < 3; i++)
    {
        printf("%d\n", numbers[i]);
    }

    if (child == 0)
    {
        free(numbers);
        kill(getpid(), SIGKILL);
    }

    free(numbers);
    return 0;
}

我试过使用free但是没用。[内存泄漏](https://i.stack.imgur.com/55H5s.png)

c memory-leaks fork free child-process
1个回答
0
投票

我相信你的问题是你的父进程在你的子进程之前完成,你不等待你的子进程结束。

您可以在父进程中使用中的等待函数来等待子进程完成执行,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

int main()
{
    int *numbers = (int *)malloc(sizeof(int) * 3);
    numbers[0] = 1;
    numbers[1] = 2;
    numbers[2] = 4;
    int child = fork();
    for (int i = 0; i < 3; i++)
    {
        printf("%d\n", numbers[i]);
    }

    if (child == 0)
    {
        free(numbers);
        return 0;
    }

    free(numbers);
    wait(NULL);
    return 0;
}

如果想得到子进程的返回值,可以给wait函数传入一个整数而不是NULL,这个整数值就是子进程返回的值

int child_result;
wait(&child_result);

当我用程序编译和运行 valgrind 时,我没有内存泄漏错误。

© www.soinside.com 2019 - 2024. All rights reserved.