c - 段错误(核心转储)错误

标签 c

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

void stringReverse(char* s){
    char tmp;
    int i = 0;
    int j = (strlen(s)-1);
    while(i>=j){
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
        i++;
        j--;
    }

}

int main(int argc, char* argv[]){
    FILE* in; /* file handle for input */
    FILE* out; /* file handle for output */
    char word[256]; /* char array to store words from the input file */

   /* checks that the command line has the correct number of argument */
    if(argc !=3){
        printf("Usage: %s <input file> <output file>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /* opens input file for reading */
    in = fopen(argv[1], "r");
    if(in==NULL){
        printf("Unable to read from file %s\n", argv[1]);
    }

    /* opens ouput file for writing */
    out = fopen(argv[2], "w");
    if(out==NULL){
        printf("Unable to read from file %s\n", argv[2]);
        exit(EXIT_FAILURE);
    }

    /* reads words from the input file and reverses them and prints them on seperate lines to the output file */
    while(fscanf(in, " %s", word) != EOF) {
        stringReverse(word);
        fprintf(out, "%s\n", word);
    }

    /* closes input and output files */
    fclose(in);
    fclose(out);

    return(EXIT_SUCCESS);
}

我不断收到段错误(核心转储)错误。我在做什么 错误的?我的输出文件也返回为空,这是不应该发生的。

我的输入是

abc def ghij 
klm nopq rstuv 
w xyz

输出应该是

cba 
fed 
jihg 
mlk  
qpon  
vutsr 
w  
zyx

最佳答案

当然你应该花一些时间来学习使用gdbvalgrind . 至于代码,不应该是while(i<=j)吗?而不是 while(i>=j)在第 9 行?

解释:

Barmar 和 loginn 之间的讨论实际上很好地解释了为什么会出现段错误。逻辑while(i>=j)是错误的,但除非输入文件中有单个字符(例如示例输入中的“w”),否则不会出现段错误。为什么单个字符输入会导致段错误?因为然后你用满足循环条件的 i = 0 和 j = 0 开始你的循环,然后进入 i = 1 和 j = -1 这也满足不正确的循环条件。此时尝试访问无效地址 (s[-1]) 将导致段错误。

如果您的输入文件中没有任何单个字符,那么您的程序将简单地运行并打印输出文件中的单词。它不会反转任何单词,因为代码不会因为错误的条件而进入执行反转的 while 循环。但它也不会导致任何段错误。

希望我已经解释清楚了。

关于c - 段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36728978/

相关文章:

c++ - 变量的 const 和 volatile 顺序

c - 二进制串联不起作用

c - 使用 strcat 时出错

c - OpenSC 与 openCryptoKI

更改文件描述符以将 STDOUT 通过管道传输到套接字?

java - Swig - 为什么我们需要声明函数两次?

c - 害怕只从我第一次运行程序时开始阅读

c - 我需要 fscanf 参数的解释

c - 多线程->调度。核心转储

c++ - 如何计算结构的偏移量