'Segmentation Fault while printing

#include <stdlib.h>
#include <stdio.h>  
#include "string.h"
//This function tries to calculate result of the floor function for floats <= 9999.
int main(int argc, char* argv[]) {
int i, j;
float k;
int x[10000];

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

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

tester(x, k);
 }

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

When I run the program it gives me segmentation fault in here:

printf("x[%d] = %d\n", k, c[k]);

Can anyone see the what problem really is?

You can see the screenshots: segmentation fault in printf



Solution 1:[1]

There are two major problems in your code.

  1. You get input from the user (scanf) as float, but actually use it as int to pass it into the function and as index for the array x.
  2. You should ALWAYS check user input from the terminal (or wherever). In this case the check should be at least, if the actual input is between 0 and 9999.

Improved version:

#include <stdlib.h>
#include <stdio.h>  
#include "string.h"

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

//This function tries to calculate result of the floor function for floats <= 9999.
int main(int argc, char* argv[]) {
    int i;
    int k;
    int x[10000];
    
    for(i = 0; i < 10000; ++i){
        x[i] = i;
    }
    
    printf("Enter a float in 0..9999: ");
    scanf("%d", &k);
    if (k >= 0 && k < 10000) {
        tester(x, k);
    } else
    {
        printf("Sorry, your input %d was invalid.", k);
    }
}

Probably that will fix your Segmentation Fault problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ThoPaz