Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segmentation Fault in C when adding an element to array

I am trying to calculate result of the floor function for floats <= 9999.

#include <stdlib.h>
include <stdio.h>   
#include "string.h"
int main(int argc, char* argv[]) {
int i, j, k;
int x[1000];

for(i = 0; i < 10000; ++i){
    x[i] = i;
}

printf("Enter a float in 0..9999: ");
scanf("%d", k);

tester(x, k);
}

int tester(int* c, int k) {
printf("x[%d] = %d\n", k, c[k]);
}

When compiler came to;

for(i = 0; i < 10000; ++i){
   x[i] = i;
}

it gives segmentation fault;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x[i] = i;

here.

I have already checked similar questions about assigning segmentation fault but I couldn’t find any solution way. Can anyone help?

>Solution :

The array x is of length 1,000, but you’re treating it in the loop as if it’s of length 10,000. Accessing x[i] for i greater than or equal to 1,000 is undefined behaviour because the index is out of the array’s range.

Thus, a segmentation fault is occurring because your program is accessing memory that it is not allowed to access.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading