C malloc 可以工作,但不应该

问题描述 投票:0回答:1

对于我的线性代数代码,我需要为下三角矩阵分配内存, 用一维数组表示。我正在尝试可以分配多少元素 偶然发现了一种奇怪的行为。如果我将 double Bottom_row_final 设置为 240.0 以上,则 malloc 失败,我的机器无法分配足够的内存,但将其设置为 410.0 malloc 不会失败,并且 在 30 次左右的迭代后初始化数组时,我的代码稍后在 for 循环中崩溃(超出 边界索引被排除为可能的错误源)。有人知道这里发生了什么事吗?

//array.c
#include<stdio.h>
#include<stdlib.h>

void vector_alloc(int N, double **pM){
  if((*pM = (double *)malloc(N*sizeof(double))) == NULL){
    printf("Fehler: malloc fehlgeschlagen!\n");
    exit(0);
  }
}

void vector_free(double **pM){
  free(*pM);
  *pM = NULL;
}

int main(void){
//-----------------------------------------------------------------------------------------------------------------------
  double grid_step=0.0125;
  double bottom_row_final=410.0;     //  230 works, 240 and above does not allocate anymore, but 410 does 

  int bottom_row_elements = (int)(bottom_row_final/grid_step)+1;
  int lower_triangular_matrix_elements = bottom_row_elements*(bottom_row_elements+1)/2;
  double *matrix;
  vector_alloc(lower_triangular_matrix_elements,&matrix);
  int index_jumper=0;
//-----------------------------------------------------------------------------------------------------------------------  
  for(int i=0;i<=bottom_row_elements;i++){      

    if(i<bottom_row_elements){
        printf("\n%d\t%d",index_jumper,lower_triangular_matrix_elements-1);
    matrix[index_jumper]=1.0;
        printf("\tInitialized with value");
    index_jumper+=(bottom_row_elements-i);
    }
  }
//-----------------------------------------------------------------------------------------------------------------------  
  vector_free(&matrix);
}

我尝试调试代码,但出现分段错误(显然),但 malloc 不应该 甚至可以为 240.0 以上的 double Bottom_row_final 分配内存

arrays c segmentation-fault malloc
1个回答
0
投票

我尝试复制你的问题,但我不能。您确定 malloc() 真的有效吗?在没有调试的情况下运行它,您是否收到错误消息?

© www.soinside.com 2019 - 2024. All rights reserved.