Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault in C while using int pointer argument

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
like image 424
user1185790 Avatar asked Jan 10 '23 02:01

user1185790


1 Answers

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.

like image 112
wallyk Avatar answered Jan 21 '23 01:01

wallyk