首页 > 解决方案 > 我不断收到分段错误:11 在尝试比较 C 中的两个数组时

问题描述

我正在尝试比较两个保存数据的数组,如果一个数组与另一个数组中的数据匹配,我希望它打印到屏幕上找到匹配的数据。我不断收到分段错误:11 并且它还打印匹配 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] != '\0';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;
}

标签: carraysloopscomparisonc-strings

解决方案


我发现了两个问题:

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

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

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


推荐阅读