4

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 Answers 3

4

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.

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

2 Comments

Oh my god, I'm such an idiot. Sorry for wasting everyone's time :-)
@user1185790: No sweat. Making mistakes is how we learn. Imagine how little you would learn if everything "just worked" the first time!
3

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.

Comments

2

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); 

Comments

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.