使用fscanf的分段故障未分配内存问题

使用fscanf的分段故障未分配内存问题,c,segmentation-fault,scanf,C,Segmentation Fault,Scanf,我试着编写这个代码,以便从文件中读取希腊字母,并使用fscanf打印发音相同的英文字母。问题是我总是犯分段错误。我错过了什么 #include <stdio.h> int main () { char s[100]; int i; FILE * myfile; myfile = fopen("/home/angelos/Downloads/λεξικο2.txt", "r"); while( fscanf(

我试着编写这个代码,以便从文件中读取希腊字母,并使用fscanf打印发音相同的英文字母。问题是我总是犯分段错误。我错过了什么

#include <stdio.h>

int main ()
{            
    char s[100];    
    int i;
    FILE * myfile;

    myfile = fopen("/home/angelos/Downloads/λεξικο2.txt", "r");

    while( fscanf(myfile, "%s", s) == 1)
        {   
            for (i=0 ; i<100 ; i++)
                { 
                    if ( s[i] == 'Α' )
                        { printf("A") ; }
                    else
                     if ( s[i] == 'Β' )
                        { printf("V") ; }
        }
}
#包括
int main()
{            
chars[100];
int i;
文件*myfile;
myfile=fopen(“/home/angelos/Downloads/λεξικο2.txt”,“r”);
而(fscanf(myfile,“%s”,s)==1)
{   

对于(i=0;i您的代码有3个严重问题

1) 您从不检查
fopen
是否成功

2) 您可以读取未初始化的有符号数据

3) 您可能会使输入缓冲区溢出

这三件事都可能导致程序失败

尝试以下更改:

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

int main ()
{            
    char s[100];    
    int i;
    FILE * myfile;

    myfile = fopen("/home/angelos/Downloads/λεξικο2.txt", "r");

    // Check that fopen went fine
    if (!myfile)
    {
         printf("Failed to open file\n");
         return 1;
    }

    while( fscanf(myfile, "%99s", s) == 1)
                         // ^^
                         // Never read more than 99 chars (i.e. 99 + a terminating null byte)
        {   
            for (i=0 ; i<strlen(s) ; i++)
                      // ^^^^^^
                      // Only iterate over the valid chars
                { 
                    if ( s[i] == 'Α' )
                        { printf("A") ; }
                    else
                     if ( s[i] == 'Β' )
                        { printf("V") ; }
        }
}
#包括
#包括
int main()
{            
chars[100];
int i;
文件*myfile;
myfile=fopen(“/home/angelos/Downloads/λεξικο2.txt”,“r”);
//检查fopen是否正常
如果(!myfile)
{
printf(“打开文件失败\n”);
返回1;
}
而(fscanf(myfile,“%99s”,s)==1)
// ^^
//永远不要读取超过99个字符(即99+一个终止的空字节)
{   

用于(i=0;iStep 1:
fscanf(myfile,“%s”,s)
-->
fscanf(myfile,“%99s”,s)
以防止缓冲区溢出。请勿访问并传递读取的数据。
用于(i=0;i
用于(i=0;s[i];i++)
。需要查看用于诊断分段错误的输入。还要测试
myfile==NULL
。检查
fopen
的返回值。不幸的是,所有这些解决方案仍然存在分段错误。该文件只是一个包含4个单词的简单txt文件。请尝试使用此精确代码。首先,它无法识别strlen当我用我从一开始就有的东西替换它时,我得到了分段错误哦,你是对的。但是刚刚尝试过它仍然分段错误更新:我忘了写一行,它返回的结果是无法打开文件。那么我该怎么办?@Angelossoulles-首先确保文件确实存在于所使用的位置。我可以e文件名包含希腊字母。我不确定这是否有问题,但您可以尝试将文件重命名为类似于
a.txt
(并同样更新程序)。是的,我使用errno代码发现它。重命名工作正常。非常感谢您宝贵的帮助!