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