本文介绍了C中的动态数组导致分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以这种方式定义了一个动态数组:
I have defined a dynamic array this way:
double *n_data ; int n_data_c = 0, n_cnt = 0; n_data_c = count_lines_of_file("abnorm"); n_data = (double *)malloc(n_data_c * sizeof(double));
我会循环计算距离,并这样做:
in a loop I calculate distance and do so:
n_cnt++; n_data[n_cnt] = distance;
但它在此处返回 segmentation fault : code> n_data [n_cnt] =距离;
but it returns segmentation fault here : n_data[n_cnt] = distance;
我想知道自己做错了什么。
I want to know if I'm doing something wrong.
推荐答案
检查返回的malloc,如果返回0,则失败。我认为,您的n_cnt更可能超出范围。如果它为负数或大于或等于n_data_c,则将出现段错误。
Check what malloc returned, if it returned 0, then it failed. More likely, I think, is your n_cnt is out of bounds. If it's negative, or greater than or equal to n_data_c, then you'll get a segfault.
这篇关于C中的动态数组导致分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!