Wahhaaj Salam - 1 year ago 74
C Question

# formula causing segmentation fault 11

I dont understand why I am getting a segmentation error 11 in the console when I enter my number 1 to 4. When I bypass the velocity formula it works but I can't find out how to fix the formula.
I have created this code for a school assignment which wants me to print the 4 struct arrays and prompt the user to pick one and then using the one the user picked to calculate the velocity of that channel and output it.

``````/*----------------------------------------
file: A4Q2.c
author: Wahhaaj Salam
description: Program presents the characteristics of four rectangular channels and prompts the user to select one of the channels and after calculate the chnnels velocity and displays results
-----------------------------------------------*/
#include <stdio.h>
#include <math.h>
// function prototypes

typedef struct
{
// variable declarations
char name[100]; // Channel name
float n; // roughness
float slope; // slope
float width; // width
float depth; // depth
} CHANNEL;

void printchannels(CHANNEL channels[4]);
float velocity(CHANNEL channels[4], int x);

void main (){
CHANNEL channels[4] =
{
{"Channel 1", 0.035, 0.0001, 10.0, 2,0},
{"Channel 2", 0.020, 0.0002, 8.0, 1.0},
{"Channel 3", 0.015, 0.0010, 20.0, 1.5},
{"Channel 4", 0.030, 0.007, 24.0, 3.0},

};
printchannels(channels);
int x;
float v;
printf("Make a selection(1 to 4):");
scanf("%f", &x);
v = velocity(channels,x);
printf("the velocity is: %f", v);
}

void printchannels(CHANNEL channels[4])
{
int i;
for ( i = 0; i <4; i++){
printf("%s ", channels[i].name);
printf("%.3f  ", channels[i].n);
printf("%.4f  ", channels[i].slope);
printf("%.1f ", channels[i].width);
printf("%.1f \n", channels[i].depth);

}

}

float velocity(CHANNEL channels[4], int x)
{
float v;
v=(channels[x-1].width/channels[x-1].depth);
v=v/(channels[x-1].width + (2*channels[x-1].depth));
v=pow(v,0.6666666666667);
v=v*(sqrt(channels[x-1].slope)/channels[x-1].n);
return v;
}
``````

You declare

``````int x;
``````

Then you wrongly scan `x` as a float: value is not likely to be within 1 and 4

``````scanf("%f", &x);
``````

then you pass the value to your routine: array out of bounds!

correct code (which protects you from user wrong inputs as a bonus) would be:

``````while(1)
{
printf("Make a selection(1 to 4):");
scanf("%d", &x);
if ((x>0) && (x<5)) break;  // boundary checking
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download