Я продолжаю получать segmentation fault: 11 при попытке сравнить два массива в C - PullRequest
0 голосов
/ 05 мая 2020

Я пытаюсь сравнить два массива, которые содержат данные, и если один массив совпадает с данными в другом массиве, я хочу, чтобы он выводил на экран, какие данные он нашел совпадение. Я продолжаю получать ошибку сегментации: 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;
}

1 Ответ

0 голосов
/ 05 мая 2020

Я обнаружил две проблемы:

count не инициализирован. Когда вы считаете запятые, вы начинаете с непредсказуемого значения. Это неопределенное поведение.

l oop over capList выходит за пределы. j l oop увеличивается до 37, но массив имеет только размер 7. Это также неопределенное поведение.

Исправив эти две проблемы, ваша программа, похоже, работает (по крайней мере, это не так. 't cra sh - я не могу точно сказать, будет ли он вести себя так, как вы предполагаете).

...