我不断收到分段错误:尝试比较 C 中的两个数组时出现 11

I keep getting segmentation fault: 11 when trying to compare two arrays in C

我正在尝试比较两个保存数据的数组,如果一个数组与另一个数组中的数据匹配,我希望它在屏幕上打印它找到匹配的数据。我不断收到 segmentation fault: 11 并且它还打印 match 1000 这是错误的。通常我正在读取一个包含更多数据的 csv 文件,但为了测试和简化它,我只是创建了更小的相似数据数组。任何帮助都会很棒。

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

#define BUFFER_SIZE 100



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

    //Setting up variables
    int i,j,count;

    /*Setting up file pointer and opening file
    //FILE *fp;
    //fp = fopen("csvTest.csv","r");
    //if(!fp){
        //printf("File did not open");
    }*/

    //Making a string buffer and getting the data from the CSV
    //and placing it into the buffer
    char buff[BUFFER_SIZE] = "1000,cap_net_raw,cap_sys_admin,cap_setpcap";
    //fgets(buff, 100, fp);
    //fclose(fp);

    //Finding out how many caps there are based off commas
    for(i=0;buff[i] != '[=10=]';i++){
        count += (buff[i] == ',');
    }
    printf("Number of caps: %d\n", count);

    //Using strtok (string token) to split the buffer string at the comma
    //Setting up an array to hold the data after the split
        char *tokptr = strtok(buff,",");
        char *csvArray[count+1];
        i = 0;
        while(tokptr != NULL){
              csvArray[i++] = tokptr;
              tokptr = strtok(NULL, ",");
        }

    //Printing the data from the array 
    printf("EUID & CAPS from CSV file: \n");
        for(j=0; j < i; j++){
            printf("%s\n", csvArray[j]);
        }

    //Getting all current caps and storing them into an array
    //cap_t caps = cap_get_proc();
    //char *capList[CAP_LAST_CAP] = {};
    char *capList[7] = {"cap_chown","cap_setfcap","cap_net_raw","cap_sys_admin",
                 "cap_setpcap","cap_net_admin","cap_sys_overide"};

    /*for(i = 0; i < CAP_LAST_CAP; i++){
        //capList[i] = cap_to_name(i);
    }*/

    //Setting the caps by comparing the csv array and checking to see if
    //there is a match in the caplist, if there is then it will set the cap
    for(i = 0; i < count; i++){
        for(j = 0; j < 37; j++){
            if(strcmp(csvArray[i],capList[j]) == 0){
                printf("Set cap to %s\n", csvArray[i]);
            }
        }
    }

   return 0;
}

我发现了两个问题:

count 未初始化。当您计算逗号时,您会从一个不可预测的值开始。这是未定义的行为。

capList 的循环越界。 j 循环上升到 37,但数组的大小仅为 7。这也是未定义的行为。

解决这两个问题后,您的程序似乎可以运行(至少,它不会崩溃——我无法确定它是否具有您想要的行为)。