. I am trying to make a program similar to 'ls', and I use pointers for doing some stuff. For some reason, when I run it I get terminated by signal SIGSEGV (Address boundary error)
. why? I'm new to C and pointers so I don't know what is going on here. the problem is with newColl, because it worked b4 I added it.
the relevant parts of my code:
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;
}
You are invoking undefined behavior by passing data having wrong type to printf()
.
The format specifier %s
expects char*
, but the function newColl
returns char
.
You should use %c
specifyer to print one character represented by an integer.
Wrong:
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
Corrected:
printf("%s%c", entity->d_name, newColl(columns, &collCounter));
What you need:
printf("%s%c", entity->d_name, newColl(columns, &collCounter));
What you did:
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
The format specifier %s
expects char*
. The function newColl()
returns char
, which is implicitly cast to int
and used as an address to fetch the contents at that location, resulting in SIGSEGV(Address boundary error) .
Check the compiler warnings.
warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
printf("%s%s", entity->d_name, newColl(columns, &collCounter));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.