[英]terminated by signal SIGSEGV (Address boundary error) when running program that uses pointers
. 我正在尝试制作一个类似于“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*
,但 function newColl
返回char
。
您应该使用%c
指定器来打印一个由 integer 表示的字符。
错误的:
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*
。 function newColl()
返回char
,它被隐式转换为int
并用作获取该位置内容的地址,从而导致SIGSEGV(Address boundary error) 。
检查编译器警告。
warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.