【发布时间】:2018-02-15 20:54:26
【问题描述】:
我们有一个任务是从一个文件中获取字符,将它向右移动一个给定的值(这在代码中是有意义的),然后将这个新值存储在一个新文件中,但我似乎是遇到分段错误,据我所知,这意味着我正在尝试访问已分配的内存之外的内存?我对 C 非常陌生,直到现在我都设法调试了这段代码,老实说,我不知道该去哪里。我什至不太明白问题是什么。
#include<stdio.h>
//Get Shift amount
//Get ifilename
//Get ofilename
//open them
//Get characters one at a time from input
//Process and shift by shift amount
int main()
{
int i;//loop value
char a[62]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//Variable with every value
int sa = 0;//Store Shift value
char ofile[30];//contain the name of output file
char ifile[30];//contain name of input file
char value;//Value to keep the current value in
printf("How far in ascii values would you like to shift?\n");
scanf("%i", sa);//Get shift
printf("What is the name of your input file located in this directory?");
scanf("%s", ifile);//get input name
printf("What would you like to name your new file?\n Do note that it will overwrite the current file named this!");
scanf("%s", ofile);//Get output name
FILE *oIfile = fopen(ifile, "r"), *oOfile = fopen(ofile, "w");
while(value = fscanf(oIfile, "%c", value) != EOF)//Check to ensure that you never reach the end of the file
{
for(i=0; i<62; i++)//loop through the list of all characters
{
if(value == a[i])//check to see if the value from the input file matches with which letter
{
value = a[i+sa] % 62;//incrase the value by the shift amount, check if its longer than 62, add remainder
break;//break the for loop so we can restart the while loop with the next letter
}
}
fprintf(oOfile, "%c");//print the new value to the output file
}
fclose(oIfile);//close input file
fclose(oOfile);//close output file
}
这个问题是由于我的 scanf 方法造成的吗?
【问题讨论】:
-
a[i+sa]看起来你可以在这里轻松地越界。也许你想在数组查找之前修改? -
“我在截止日期前”。对不起,我爱上了你,但这个网站上的帖子是永恒的。您的任务的紧迫性在这里并不重要。
-
仅供参考,分段错误是由内存问题引起的——代码读取或写入非法内存位置。这可能是从一个不存在的文件中读取,或者在这种情况下,尝试将输入写入地址“0”,而不是 int
sa的地址。 -
@bolov 回复:只需 1 封信就可以成为幽默的 comment:I fell for you 与 I feel for you
-
@chux 好吧,我能说什么,紧迫感很性感? :)