Seung Kwak Seung Kwak - 7 months ago 65
C Question

Segmentation fault of pointer&char

Im trying to make the program that extract filenames by inputing some folderpath.

The outcome is fine, but the problem is at the end of outcome, there's some segmentation fault that i cant figure out.

Here's what I wrote in.

#include <stdio.h>
#include <dirent.h>

int main() {

char folderpath;
printf("enter the path : \n");

DIR *d;
struct dirent *dir;
d = opendir(&folderpath);
if (d)
while((dir= readdir(d)) != NULL)
printf("%s\n", dir->d_name);


return 0;

And, result is like

enter the path : /Users/gui/Desktop/extract/extract
Segmentation fault: 11

Sorry for asking really simple question like this, which I tried hard to figure out but I cant.

Thanks for reading this question.
Best Regard.


When you call scanf with the %s format specifier, it expects a pointer to an array of characters. What you're passing is the address of a single character. So it writes past the memory location of that variable into whatever happens to be next to it. This invokes undefined behavior.

You need pass a character array to scanf:

char folderpath[256];
printf("enter the path : \n");


d = opendir(folderpath);