0

I'm fairly new to c and I'm trying to understand and grasp malloc. My program takes an integer x input, then loops until x is met while also taking other integer inputs. I then do various calculations. However I'm getting a segmentation fault and I don't understand why.

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

int main(void)
{

    calculations();
}

void calculations()
{

    int i;
    int x;
    int total = 0;
    double squareRoot;
    double overall;

    scanf("%d", &x);

    int* array = malloc(x * sizeof(int));

    if (!array) {
        printf("There isn't enough memory \n");
        return;
    }

    int c = 0;

    while (c < x) {

        scanf("%d", &array[i]);

        total = array[i] * array[i];
        c++;
    }

    squareRoot = sqrt(total);
    array = realloc(array, x * sizeof(int));

    int b = 0;

    while (b < x) {

        overall = array[i] / squareRoot;
        printf("%.3f ", overall);

        b++;
    }
}
12
  • 1
    Do you have a debugger? That would tell you which line triggered the segmentation fault. Commented Mar 1, 2017 at 18:27
  • What's with the weird alignment and missing indent? Commented Mar 1, 2017 at 18:29
  • In array = realloc(array, x* sizeof(int)); if you intended to extend - and then index - the memory allocation, it does not give any more memory, being the same allocation as the original array = malloc(x * sizeof(int)); Commented Mar 1, 2017 at 18:32
  • Valgrind will help you narrow down memory access errors like this. Commented Mar 1, 2017 at 18:32
  • @SouravGhosh Sorry I forgot to post my indented code. I've edited it now. Commented Mar 1, 2017 at 18:35

1 Answer 1

3

The problem is with

 scanf("%d", &array[i])

where, the value of i is indeterminate.

To elaborate, i is an uninitialized local variable and unless initialized explicitly, the contents remain indeterminate. Attempt to use that value, in this scenario, would lead to invokes undefined behavior.

Even if you initialize i, you never operated on i, so all the changes will be overwritten on a fixed index. You got to take care of this case, too.

Solution: Looking at the code, it appears, you may want to use

scanf("%d", &array[c]);

instead.

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

1 Comment

Thanks this fixed my issue! I changed all the array[i] to array[c] however when I now run my program I only get 0.000 as my output? Any idea why this is?

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.