I know - another segmentation fault question...
I am trying to run my professor's function enterValue
, but keep receiving a segmentation fault error. Am I the one doing something wrong, or is there a bug that I'm not catching in his code? Note that the declaration int* length;
actually was written in his original code as int length;
. Given that the final argument valuePtr
is intended to be a pointer to an int, that's what I thought the argument length
should be defined as.
#include <stdlib.h>
#include <stdio.h>
#define MAX_LINE 256
char line[MAX_LINE];
int* length;
void enterValue (const char* descriptionPtr,
int min,
int max,
int* valuePtr
)
{
do
{
printf("Please enter the %s (%d-%d): ",descriptionPtr,min,max);
fgets(line,MAX_LINE,stdin);
*valuePtr = strtol(line,NULL,10);
}
while ( (*valuePtr < min) || (*valuePtr > max) );
}
int main ()
{
enterValue ("number of numbers", 1, 256, length);
return(EXIT_SUCCESS);
}
When I run this, I get the following:
Please enter the number of numbers (1-256): 4
Segmentation fault
Yep, you should have left the original declaration of int length
. Pass a pointer to it in the call with
enterValue ("number of numbers", 1, 256, &length);
That makes the argument a pointer to an int, and allows the function to write into the variable.
My making length a pointer—and especially not initializing where it points—you have created a "write to random memory" algorithm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With