Home > Enterprise >  Segmentation Fault in C when adding an element to array
Segmentation Fault in C when adding an element to array

Time:03-26

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;

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?

CodePudding user response:

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.

CodePudding user response:

The variable k is initialised and when getting input "&" is missing in the scanf statement. This might have come under segmentation fault since the value "k" is passed in the function tester(). Generally in C lang, we get input with "&", unless if it is a string you don't necessarily mention that in the scanf statement!!.

  • Related