You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在函数中realloc结构体?添加字典词触发内存错误求助

问题分析与修复

你的代码出现0xC0000005错误(内存访问违规),核心问题集中在指针操作错误和内存分配不当,以下是具体问题和修复方案:

错误点梳理

  • 二级指针访问错误:adauga_cuvant函数中,dictionar是二级指针,直接dictionar[(Lungime)]会访问不属于你的内存空间,正确方式是先解引用得到字典数组的一级指针,再访问对应下标。
  • 数组下标越界:新增元素的下标应该是Lungime - 1(数组从0开始计数,当长度变为Lungime时,最后一个元素的索引是长度减1)。
  • 字符串内存分配不足:malloc(strlen(cuvant)*sizeof(char *))有两个问题:一是误用sizeof(char*)(指针大小)而非sizeof(char)(字符大小);二是没给字符串结束符\0预留位置,必须分配strlen(cuvant)+1字节。
  • 内存分配未做错误检查:realloc和malloc可能返回NULL,直接使用会导致崩溃。

修复后的完整代码

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

struct dictionary_entry {
    char *word;
    int priority;
};

void adauga_cuvant(struct dictionary_entry **dictionar, int Lungime, char cuvant[21]) {
    // 重新分配内存并检查是否成功
    struct dictionary_entry *temp = realloc(*dictionar, Lungime * sizeof(struct dictionary_entry));
    if (temp == NULL) {
        printf("内存分配失败!\n");
        return;
    }
    *dictionar = temp;

    // 计算新元素的索引(数组从0开始)
    int new_index = Lungime - 1;
    // 分配字符串内存(包含结束符)并检查
    (*dictionar)[new_index].word = malloc((strlen(cuvant) + 1) * sizeof(char));
    if ((*dictionar)[new_index].word == NULL) {
        printf("字符串内存分配失败!\n");
        return;
    }
    strcpy((*dictionar)[new_index].word, cuvant);
    (*dictionar)[new_index].priority = 1;
}

int main() {
    int N, i;
    char aux[21];
    struct dictionary_entry *dictionary = NULL;

    scanf("%d", &N);
    // 初始化字典内存并检查
    dictionary = malloc(N * sizeof(struct dictionary_entry));
    if (dictionary == NULL) {
        printf("初始化内存失败!\n");
        return 1;
    }

    for (i = 0; i < N; i++) {
        scanf("%s", aux);
        dictionary[i].word = malloc((strlen(aux) + 1) * sizeof(char));
        if (dictionary[i].word == NULL) {
            printf("字符串内存分配失败!\n");
            return 1;
        }
        strcpy(dictionary[i].word, aux);
        dictionary[i].priority = 0;
    }

    scanf("%s", aux);
    N++;
    adauga_cuvant(&dictionary, N, aux);

    for (i = 0; i < N; i++) {
        printf("%s %d\n", dictionary[i].word, dictionary[i].priority);
        // 释放每个字符串的内存
        free(dictionary[i].word);
    }
    // 释放字典数组的内存
    free(dictionary);

    return 0;
}

额外优化

  • 新增内存分配失败的检查逻辑,避免程序直接崩溃。
  • 添加内存释放代码,解决内存泄漏问题。

内容的提问来源于stack exchange,提问作者vasile ion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 14:30:57