【发布时间】:2017-05-09 18:05:31
【问题描述】:
我必须为我的 uni 编程课程编写代码,而且我还是个初学者,所以我需要一些帮助来弄清楚为什么 'word1' 的值会在程序仍在运行时消失。我必须编写一个程序来打开一个 .c 文件并计算我保存在 .txt 文件中的特定保留字。代码是:
int countResWords(FILE *filep){
int count=0;
char word1[20],word2[20],*pos,*token,*pch,*pch2;
FILE *rp;
rp=fopen("reservedWords.txt","r+");
if(rp==NULL){
perror("File cannot be opened.");
return -1;
}
else{
while(!feof(rp)){
fscanf(rp,"%s",&word1);
count=0;
while(!feof(filep)){
fscanf(filep,"%s",&word2);
if((pch=strchr(word2,'('))!=NULL){
token=strtok(word2,"(");
while(token!=NULL){
if((pch2=strchr(token,')'))!=NULL) strtok(token,")");
if(strcmp(token,word1)==0) count++;
token=strtok(NULL,"(");
}
}else if(strcmp(word2,word1)==0) count++;
}
printf("The reserved word %s was used %d times in the given code.",word1,count);
rewind(filep);
}
}
fclose(rp);
}
int main(int argc, char *argv[]) {
char filename[100];
FILE *fp;
puts("Give a FILE NAME with its FULL PATH.");
scanf("%s",&filename);
fp=fopen(filename,"r+");
if(fp==NULL){
perror("File cannot be opened.");
return -1;
}
else countResWords(fp);
fclose(fp);
}
我目前正在测试的 .c 文件是:
#include <stdio.h>
#include <stdlib.h>
void selection(void);
void enterText(void);
void enterVoc(void);
void correctText(void);
void statistics(void);
void addWord(void);
void replaceWord(void);
void count(void);
void selection(void){
puts("selection");
}
void enterText(void){
puts("enterText");
}
void enterVoc(void){
puts("enterVoc");
}
void correctText(void){
puts("correctText");
}
void statistics(void){
puts("statistics");
}
void addWord(void){
puts("addWord");
}
void replaceWord(void){
puts("replaceWord");
}
void count(void){
puts("count");
}
int main(int argc, char *argv[]) {
selection();
enterText();
enterVoc();
correctText();
statistics();
addWord();
replaceWord();
count();
return 0;
}
在某处,变量 word1 失去了它的值,并且在 countResWords 函数底部的打印中,它不会像 word1 不存在一样打印它。
【问题讨论】:
-
scanf("%s",&filename);-->scanf("%99s",filename); -
word最多可以容纳 19 个字符(加上一个空终止符)。如果您扫描的 C 代码看起来像您在此处发布的代码,那么您将超过该限制:scanf("%s", ...)将所有非空格视为单词,因此字符串if((pch=strchr(word2,'('))!=NULL){将溢出缓冲区。 -
所以这不是什么严重的事情。 -- 这是未定义的行为,而且很严重。在您的情况下,您只是覆盖了其他内容,但是溢出缓冲区很可能会导致程序崩溃。您应该始终强制您保持在有效的数组范围内..
-
如果您想将您的问题标记为“已解决”,请发布答案并将答案标记为“已接受”。请不要在问题中编辑答案,也不要在标题中添加
[resolved]之类的伪标签。