0

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.

2

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

1 Comment

n_data_c is 7 as my file has 7 lines and n_cnt is 1 at first iteration and then it returns segfault.
0

n_data_c = count_lines_of_file("abnorm");

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

3 Comments

@G one: I checked it, it returns 7 as my file has 7 lines.
int n_data_c = 7, n_cnt = 0; n_data = (double *)malloc(n_data_c * sizeof(double)); n_cnt++; n_data[n_cnt] = 10; I tried this and its not giving me any seg fault printf("%f", n_data[n_cnt]);
Did you check passing of parameters into the calculatedistance() are they correct??
0

Just try printing the value of n_data_c before mallocing.

1 Comment

I checked it, it returns 7 as my file has 7 lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.