简体   繁体   English

C分割错误11

[英]C segmentation fault 11

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

int numExperiment=1;

int main(int argc, const char * argv[])
{
    char* experiments[20];
    int data[10][20];
    char* input;
    char* endof = "***END***";

    do {
        input=fgets(input, 20, stdin);

        if (numExperiment%2 != 0) {
            experiments[numExperiment-1]=strdup(input);
        }
        else {
            int k=0;
            while ((data[k][numExperiment-1]=strsep(&input, " ") !=NULL)) {
               k++;
            }
        }

        numExperiment++;
    } while (strcmp(input, endof)!=0);
    return 0;
}

I wrote this code and it compiles without issue but when I run it I keep getting this error: 我编写了这段代码,并且可以毫无问题地进行编译,但是当我运行它时,却不断出现此错误:
"Segmentation Fault: 11". “分段错误:11”。

What this code is supposed to do is read a file and put all data on odd lines to one array and data on even lines on 2d arrays. 此代码应该做的是读取一个文件,并将所有奇数行上的数据放入一个数组,将偶数行上的数据放入2d数组。 I'm using command line redirection to read the file. 我正在使用命令行重定向来读取文件。

If anyone could point me in the right direction on how to correct this, that'd be great. 如果有人可以向我指出正确的解决方法,那就太好了。

EDIT 1: I made a changes suggested below regarding allocating memory and fgets but i'm still getting segmentation fault 11. 编辑1:我对分配内存和fgets进行了以下更改建议,但仍然遇到分段错误11。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 1000

int numExperiment=1;

int main(int argc, const char * argv[])
{

    char* experiments[20];

    int data[10][20];
    char* input=malloc(N);
    char* endof="***END***\n";


    do {




        if (fgets(input, N, stdin) == NULL) break;


        if (numExperiment%2 != 0) {
        experiments[numExperiment-1]=strdup(input);
        }

        else {
            int k=0;
            while ((data[k][numExperiment-1]=strsep(&input, " ") !=NULL)) {
                k++;
            }


        }


        numExperiment++;



    } while ((fgets(input, N, stdin) != NULL) && (strcmp(input, endof)!=0));

    free(input);




    return 0;
}

No allocated memory @amdixon 没有分配的内存@amdixon

// char* input;
#define N 1000
char* input = malloc(N);
do {
   ...
} while (strcmp(input, endof)!=0);
free(input);

Bad use of fgets() 滥用fgets()

do {
  // input=fgets(input, 20, stdin);
  if (fgets(input, N, stdin) == NULL) break;
   ...
} while (strcmp(input, endof)!=0);

Likely wrong endof string. 可能是错误的endof字符串。

// char* endof="***END***";
char* endof = "***END***\n";  // Add \n for `fgets()`

Suggest do while re-write 建议改写时do while

while (fgets(input, N, stdin) != NULL) && strcmp(input, endof)!=0) {
   ...
}
char* input;
input=fgets(input, 20, stdin);

You have declared input , but not allocated memory for it. 您已经声明了input ,但是没有为其分配内存。

Do either 要么做

char input[20];

or 要么

char * input;
input = malloc(20);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM