2015-04-03 41 views
0

此分配要求我们只使用我们被告知使用的特定变量。这意味着我们不能创造我们自己的任何一个。这是导致段错误的代码:scanf在文件中读取时给出分段错误

int mem[100]; 
    int *instructionCounter; 
    int *instructionRegister; 
    int *operationCode; 
    int *operand; 
    char str[20]; 
    memset(str, 0 , 20); 
    scanf("%d %s %d" , instructionCounter, str, operand); //this is where the error occurs 

我尝试使用fgets而不是scanf来读取字符串。我成功读取了字符串,并试图根据需要使用sscanf来解析它。但是,由于int指针实际上并不指向任何变量,因此我也收到了分段错误。但正如我所说,我不能创建比上面列出的任何其他变量。这就是我采取这种方法的原因。

我该怎么做才能避免这种分段错误?除了scanf还有什么办法可以解决这个问题吗?谢谢你的帮助。

+3

你的整数指针不指向任何地方,所以运行时的崩溃抱怨。这个是正常的。实际上,你需要整数变量(而不是指向整数的指针),然后传递'&instructionCounter'。字符串不需要&符号,所以'str'是可以的。 memset()并不是真的有必要,尽管它也没有害处。您应该使用'%19s'而不是'%s'来防止事故发生(缓冲区溢出事故)。 – 2015-04-03 02:04:13

+0

你有没有试过把这些指针指向实际的'int',比如'mem'数组中的那些? – SleuthEye 2015-04-03 02:06:10

回答

2

C是一种指针语言,在玩指针之前,请记住,您需要为指针指定一个分配的内存区域,以确保它们在进程的虚拟内存地址空间中引用有效的内存地址。

因此,你的代码应该是这样的:

int mem[100];      // allocated in stack 
int instructionCounter;   // allocated in stack 
int instructionRegister;   // allocated in stack 
int operationCode;    // allocated in stack 
int operand;      // allocated in stack 
char str[20];      // allocated in stack 

memset(str, '\0' , sizeof(str)); 
if (scanf("%d %s %d" , &instructionCounter, str, &operand) == 3) 
    …use the values… 
else 
    …report erroneous input… 
1

这里就是我得到当我打开了警告编译代码:

$ make CC=clang 
clang -fsanitize=address -g -Wall -Wextra -Wno-unused-variable -Wno-unused-parameter -c -o testme.o testme.c 
testme.c:15:24: warning: variable 'instructionCounter' is uninitialized when used here [-Wuninitialized] 
    scanf("%d %s %d" , instructionCounter, str, operand); //this is where the 
         ^~~~~~~~~~~~~~~~~~ 
testme.c:9:28: note: initialize the variable 'instructionCounter' to silence this warning 
    int *instructionCounter; 
         ^
          = NULL 
testme.c:15:49: warning: variable 'operand' is uninitialized when used here [-Wuninitialized] 
    scanf("%d %s %d" , instructionCounter, str, operand); //this is where the 
               ^~~~~~~ 
testme.c:12:17: note: initialize the variable 'operand' to silence this warning 
    int *operand; 
       ^
       = NULL 
2 warnings generated. 
clang -fsanitize=address testme.o -o testme 

注意,编译器不希望你可以使用这些未初始化的变量,但是它的解决方案解决了这个问题,但不能解决这个问题。您还必须分配这些变量。

试试这个:

int instructionCounter; 
int operand; 
char str[20]; 
memset(str, 0 , 20); 
scanf("%d %s %d" , &instructionCounter, str, &operand);