c - 我不断收到分段错误: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;
}
解决方案
我发现了两个问题:
count
未初始化。当您计算逗号时,您从一个不可预测的值开始。这是未定义的行为。
循环超出capList
范围。j
循环上升到 37,但数组的大小仅为 7。这也是未定义的行为。
解决了这两个问题,您的程序似乎可以工作(至少,它不会崩溃——我不能确定它是否具有您想要的行为)。
推荐阅读
- python - 二十一点游戏的“IndexError:列表索引超出范围”
- go - 为什么 encoding/json 将切片编组为 base64?
- html - 将数据加载到 html 页面上的图表中
- javascript - 单击 asp:button 时显示和隐藏面板
- c++ - 如何在 C++ STL 的集合中找到有序的后继或前驱
- r - 从 IC2 函数中提取数字
- regex - 正则表达式:我怎样才能匹配第一个
- shell - 如何删除名称中包含 Ctrl-M 的文件?
- r - 如何使用在 r 中重复的另一个数据框中的特定列更新数据框中的新列?
- cassandra - 在 Cassandra 中,与压缩期间的行/单元墓碑相比,分区墓碑本质上是否更便宜?