Dynamic array in C cause segmentation fault

别来无恙 提交于 2019-12-13 04:03:51

问题


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;

but it returns segmentation fault here : n_data[n_cnt] = distance;

I want to know if I'm doing something wrong.


回答1:


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.




回答2:


You are overrunning your array buffer..

Compare n_cnt with n_data_c and only access the array if n_cnt < n_data_c/

n_cnt++;
if (n_cnt < n_data_c)
{
n_data[n_cnt] = distance;
}



回答3:


n_data_c = count_lines_of_file("abnorm");

this is generating the segmentation fault. Check the value of n_data_c




回答4:


Just try printing the value of n_data_c before mallocing.



来源:https://stackoverflow.com/questions/21872616/dynamic-array-in-c-cause-segmentation-fault

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!