J.Williams J.Williams - 1 year ago 78
C Question

C program :segmentation fault

Im new to C programing and im getting a segmentation fault somewhere in my code. The program uses a return function to ask a user for the start of how much money they have in their bank account. later I will add code to calculate the interest.Thanks for looking at this for me as im having lots of trouble finding out why im getting this error.

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

int getPV()
int d;
int start;
printf("Start: ");
scanf("%d", start);
d = start;
return d;

int main()
int pv;
pv = getPV();
return 0;

sps sps
Answer Source

When you call scanf, you need to pass the address of the variable to which you want to store the value.

That means, if you want to store the value in variable start, you need to pass the address of start to scanf.

You can get the address of a variable using the & operator. So you need to change you scanf to:

scanf("%d", &start);

You get segmentation fault when using scanf("%d", start); because, start is an automatic variable and will have a garbage (random) value in it before you assign some value to it. scanf will treat this random value as the address to which the user entered value has to be stored. Now when scanf tries to store user entered value to this random address location, you get segmentation fault, because in most likelihood your program is not allowed to access that address location.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download