接收分段错误:11

时间:2019-11-21 23:10:17

标签: c

我有这段代码,但是对于某些输入文件,我不断遇到分段错误:11。 Xcode在此行中运行后显示错误:

st[i] = ch;

我所有的代码:

#include <stdio.h>
#include <string.h>
#define MAX 10000


void string_reverse(char st[]);

int main (int argc, char** argv) {


    char line[MAX];
    char reverse[MAX]="",temp[MAX];
    int i,j;
    /*
    if(argc < 3)
    {
        printf("per mazai argumentu \n");
        return 0;
    }*/

    FILE *in  = fopen("input.txt", "r");
    FILE *out = fopen("output.txt", "w");
    while(fgets(line, 255, in))
    {

        size_t n = strlen(line);

        for(i = 0; i < n; i++) {

            for(j = 0; i < n && line[i]!=' '; ++i,++j) {

                temp[j] = line[i];

            }

            temp[j] = '\0';

            string_reverse(temp);

            strcat(reverse, temp);
            strcat(reverse, " ");
        }
    }
    fprintf(out, "%s\n",reverse);

    return 0;
}


/*apversti */
void string_reverse(char st[]) {
    int i;
    char ch;

    size_t j  = strlen(st)-1 ;
    i = 0;

    if(st[j]=='\n')
    {
        st[j]='\n';
        j--;
    }
    while(i < j) {
        ch = st[j];
        st[j] = st[i];
        st[i] = ch;
        i++;
        j--;

    }
}

2 个答案:

答案 0 :(得分:0)

问题是,当我的文本行以''开头时,size_t j = strlen(st)-1 ;溢出了。

答案 1 :(得分:0)

以下建议的代码:

  1. 干净地编译
  2. 执行所需的功能

现在是建议的代码:

#include <string.h>

void string_reverse(char st[]) 
{
    for( size_t i = 0, j = strlen( st ); i<j; i++, j-- )
    {
        char temp = st[i];
        st[i] = st[j];
        st[j] = temp;
    }
}