4
votes

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
3

3 Answers

4
votes

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.

3
votes

The integer pointer is not pointing to anything when you call entervalue function. you have to have length = &some_integer; so that integer pointer length points to some integer.

2
votes

Two mistakes I see, first length should not be not a pointer

int length;

Second, pass the address of length, as you want the function to modify length

enterValue ("number of numbers", 1, 256, &length);