0

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?

4
  • 2
    Welcome to world of magic numbers in the code. int x[1000]; and for(i = 0; i < 10000; ++i) Time to count 0 digits. Commented Mar 26, 2022 at 8:13
  • you indexing 10.000 but your array is 1000. You should change your printf Enter a float to integer since %d in scanf interprets input as decimal. Commented Mar 26, 2022 at 8:15
  • "%d" (integer in decimal format) is wrong format specifier for float – you need to use "%f" instead, otherwise undefined behaviour. Commented Mar 26, 2022 at 8:16
  • The mismatch between 1000 and 10000 is the reason why one should use constants for – and for iterating over arrays preferrably deduce the size from the array itself: sizeof(array)/sizeof(*array). Commented Mar 26, 2022 at 10:12

2 Answers 2

2

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.

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

Comments

0

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!!.

Comments

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.