c - 数组的最大大小 - 段错误

标签 c memory memory-leaks segmentation-fault malloc

我的代码遇到一些问题:

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

void union1(int belongs[],int c1,int c2, int n);

int main()
{
int i=0;
    int j=0;
    int N, num_AERO, num_E;
    if (scanf("%d", &N) != 1) { exit(1); }
    if (scanf("%d", &num_AERO) != 1) { exit(1); }
    int custoAERO[num_AERO];
    for (i = 0; i < num_AERO; i++) 
    {
        int id_aero, cst_aero;
        if (scanf("%d %d", &id_aero, &cst_aero) != 2) { exit(1); }
        custoAERO[i] = cst_aero;
    }
    if (scanf("%d", &num_E) != 1) { exit(1); }
    int *matriz_estradas[N];
    for (i = 0; i < N; i++) 
    {
        matriz_estradas[i] = malloc(sizeof(*matriz_estradas[i]));
    }

    int cid_a, cid_b, cust;
    for(i=0; i< num_E; i++)
    {
        if (scanf("%d %d %d", &cid_a, &cid_b, &cust) != 3) { exit(1); }
        matriz_estradas[cid_a -1][cid_b -1] = cust;
        matriz_estradas[cid_b -1][cid_a -1] = cust;
    }
    for(i=0; i<N; i++)
    {
        int cidade_sozinha = 0;
        for(j=0; j<N; j++)
        {

            if(matriz_estradas[i][j]>0 || matriz_estradas[j][i]>0)
                cidade_sozinha = 1;
        }
        if(cidade_sozinha==0)
        {
            if((sizeof(custoAERO)/sizeof(int))<i+1)
            {
                printf("Insuficiente\n");
                return EXIT_SUCCESS;
            }
        }
    }

代码工作正常,但是当 N 的值太高时,在分配时会出现段错误错误

    for (i = 0; i < N; i++) 
    {
        matriz_estradas[i] = malloc(sizeof(*matriz_estradas[i]));
    }

我可以在数组中分配的最大内存是否有上限?

最佳答案

您需要更正此陈述

matriz_estradas[i] = malloc(sizeof(*matriz_estradas[i]));

matriz_estradas[i] 尚未分配内存,并且 *matriz_estradas[i] 尝试从未分配的内存中访问值

关于c - 数组的最大大小 - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43737467/

相关文章:

c - 有人记得 Visual C 版本 5 中 CL.EXE 的选项吗?

android - ndk 中的 LocalBroadcastManager

c# - 为什么客户端在不同的服务器上使用更多的内存?

C++ 动态分配不匹配 : Is this problematic?

取消设置后 PHP 释放内存

将 ASM 转换为 C(不是逆向工程)

用于链接和释放的 C 矩阵函数设计

android - Android中每个进程需要2MB内存?

objective-c - 使用 Objective-C 以编程方式释放系统内存

java - 将大行写入文件