MST
星途 面试题库

面试题:C语言指针的指针在函数参数传递中的复杂应用

假设有一个函数,其功能是通过指针的指针来修改一个字符串数组(数组中的每个字符串都是动态分配的),函数需要能增加新的字符串到数组中,同时要处理内存的重新分配。请编写该函数,并说明如何处理可能出现的内存泄漏问题。
44.0万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 函数声明
void addString(char ***strings, int *size, int *capacity, const char *newString);

int main() {
    char **strings = NULL;
    int size = 0;
    int capacity = 0;

    addString(&strings, &size, &capacity, "Hello");
    addString(&strings, &size, &capacity, "World");

    for (int i = 0; i < size; i++) {
        printf("%s\n", strings[i]);
        free(strings[i]);
    }
    free(strings);

    return 0;
}

void addString(char ***strings, int *size, int *capacity, const char *newString) {
    if (*size >= *capacity) {
        // 重新分配内存
        *capacity = (*capacity == 0)? 1 : *capacity * 2;
        *strings = (char **)realloc(*strings, *capacity * sizeof(char *));
        if (*strings == NULL) {
            perror("realloc");
            exit(EXIT_FAILURE);
        }
    }

    // 为新字符串分配内存
    (*strings)[*size] = (char *)malloc(strlen(newString) + 1);
    if ((*strings)[*size] == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }

    // 复制新字符串
    strcpy((*strings)[*size], newString);
    (*size)++;
}

内存泄漏处理说明

  1. 字符串数组内存管理
    • 使用realloc函数来动态调整字符串数组strings的大小。当数组已满(*size >= *capacity)时,将其容量翻倍。如果realloc失败,打印错误信息并退出程序,避免在后续操作中使用未正确分配的内存。
  2. 单个字符串内存管理
    • 为每个新加入的字符串分配内存时,使用malloc。如果malloc失败,同样打印错误信息并退出程序。
  3. 释放内存
    • 在使用完字符串数组后,需要遍历数组,释放每个字符串的内存,然后释放字符串数组本身的内存。如在main函数中,通过for循环释放每个字符串,最后释放strings。这样可以确保没有内存泄漏。