MST
星途 面试题库

面试题:C语言中Linux进程正常退出时如何释放动态分配的内存资源

在Linux环境下使用C语言编程,假设进程中有通过malloc动态分配的内存,当进程正常退出(例如调用exit函数)时,如何确保这些动态分配的内存资源被正确释放?请写出关键代码片段说明。
33.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

在Linux环境下,当进程正常退出时,系统会自动回收该进程占用的所有资源,包括通过malloc动态分配的内存。因此,一般情况下,在进程退出时不需要显式地释放通过malloc分配的内存。

以下是一个简单示例代码:

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

int main() {
    int *ptr = (int *)malloc(sizeof(int));
    if (ptr == NULL) {
        perror("malloc");
        return 1;
    }
    *ptr = 42;
    printf("Allocated memory and set value: %d\n", *ptr);
    // 这里不手动释放ptr指向的内存,直接退出进程
    exit(0);
}

然而,在实际应用中,为了养成良好的编程习惯,并且在进程未正常退出(如崩溃等情况)时避免内存泄漏,应该在程序中合适的位置手动释放动态分配的内存。例如:

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

int main() {
    int *ptr = (int *)malloc(sizeof(int));
    if (ptr == NULL) {
        perror("malloc");
        return 1;
    }
    *ptr = 42;
    printf("Allocated memory and set value: %d\n", *ptr);
    free(ptr); // 手动释放内存
    ptr = NULL; // 防止悬空指针
    exit(0);
}