。我正在尝试制作一个类似于ls的程序,并且我使用指针来做一些事情。出于某种原因,当我运行它时,我会得到terminated by signal SIGSEGV (Address boundary error)
。为什么?我是C和指针的新手,所以我不知道这里发生了什么。问题出在newColl上,因为它在b4上有效,我添加了它。
我的代码的相关部分:
char newColl(int columns, int* counter) {
if (columns == *counter) {
*counter = 0;
return 'n';
}
return ' ';
}
int main(int argc, char* argv[]) {
char path[256] = "."; // MAKE STRLEN OF ARG
int all = 0;
int columns = 1;
int collCounter = 0;
DIR* dir = opendir(path);
if (dir == NULL) return 1;
struct dirent* entity;
entity = readdir(dir);
while (entity != NULL) {
if (all != 1 && entity->d_name[0] != '.')
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
if (all == 1)
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
entity = readdir(dir);
collCounter++;
}
return 0;
}
您通过向printf()
传递类型错误的数据来调用未定义的行为。
格式说明符%s
需要char*
,但函数newColl
返回char
。
您应该使用%c
说明符来打印一个由整数表示的字符。
错误:
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
更正:
printf("%s%c", entity->d_name, newColl(columns, &collCounter));
您需要什么:
printf("%s%c", entity->d_name, newColl(columns, &collCounter));
你做了什么:
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
格式说明符%s
需要char*
。函数newColl()
返回char
,它被隐式转换为int
,并用作获取该位置内容的地址,从而导致SIGSEGV(地址边界错误(。
检查编译器警告
warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
printf("%s%s", entity->d_name, newColl(columns, &collCounter));