Home > front end >  Segmentation Fault while printing
Segmentation Fault while printing

Time:03-28

#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

CodePudding user response:

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.

  • Related