数字输入的分段错误

时间:2011-06-01 10:16:14

标签: c segmentation-fault strtol

我正在用C编写我的第一个程序,它给了我很多问题。 这很简单;输入一个数字,输出将是Fibonacci序列中相应的术语,其中第一个和第二个术语是1.只要我没有输入除数字之外的任何东西作为输入,它就开始工作;字母或特殊字符导致分段错误。为了解决这个问题,我试图拒绝所有非数字输入,因为我找不到这样做的功能,所以我自己做了。不幸的是,它现在在给出数字输入时给出了分段错误,并且所有非数字输入都被读为26。

编译器,带有迂腐警告的gcc,只抱怨我的评论。 我已经使用GDB将分段错误缩小到:

return strtol(c, n, 10);

任何有助于识别问题并在下次避免问题的帮助都将不胜感激。

守则:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
  calcTerm(); //Run calcTerm()
  return 0; //Return value & exit
}

int fibTerm(int term)
{
  //Declare Variables
  int a = 0;
  int b = 1; 
  int next;
  int x;

  //Calculate the sequence
  for (x = 0; x <= (term - 2); x++)
  {
    next = a + b;
    a = b;
    b = next;
  }

  return next; //return the requested output
}

int calcTerm()
{
  //declare variables
  int in;
  char rawIn[256];
  char **n;
  int out;

  printf("Input the term you want to find:\n"); //request input

  //get input
  fgets(rawIn, 3, stdin);

  //define variables
  in = isNumeric(rawIn); /*strtol(rawIn, n, 10) works*/
  out = fibTerm(in);

  //print result
  printf("Term %i " "is %i", in, out);
}

int isNumeric(char test[256])
{
  //declare variables
  char validChars[10] = "0123456789"; //valid input characters
  char *c = test;
  char **n;

  if (strpbrk(test, validChars)) //if input contains only valid characters ?
  {
    return strtol(c, n, 10); //return the input as an integer
    //segmentation fault; strtol_l.c: no such file
  }
  else
  {
    printf("Please only input numbers."); //error message
  }

}

2 个答案:

答案 0 :(得分:4)

n是单元化的,它指向无处。 strtol将尝试写入n指向的内存地址,该地址可能位于内存中的任何位置,并且可能不会指向允许您编写的区域。只需在那里传递一个空值(即strtol(c, 0, 10))。

顺便说一句,我尝试使用sscanf来解析数字; sscanf返回成功解析的标记数,因此如果您将零作为返回值,则该数字无效。 E.g:

const char* my_string = "  123";
const char* my_invalid_string = "spam spam spam";
int number;
sscanf(my_string, "%d", &number);    // this should return 1
sscanf(my_invalid_string, "%d", &number); // this should return 0

既然您正在阅读标准输入,那么您可以跳过将字符串存储在字符串中,然后调用sscanf,您只需使用scanf直接解析标准输入。

答案 1 :(得分:1)

您获得输入1的随机输出,因为在fibTerm中永远不会输入循环(for (x = 0; x <= (term - 2); x++)term == 1)。因此,将返回未初始化的next

相关问题