#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main(){
struct stat *something;
stat("/etc/profile", something);
printf("%d\n", something->st_gid);
free(something);
return 0;
}
$ ./a.out
Segmentation fault
I learned from this post that I need to allocate memory using malloc, so I changed it to as below, and it works:
- struct stat *something;
+ struct stat *something = malloc(sizeof(struct stat));
In a prior but related exercise, I did not use a malloc, and it had worked. I am lost! Why don't I need malloc for the line "*struct dirent b;" below?
Or, to rephrase, how can we know the payload is too much and to use malloc?
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]){
if (argc != 2){
printf("Error. Syntax: ls <somefolder> \n");
return 1;
}
DIR *a = opendir(argv[1]) ;
if (a == NULL){
printf("error. cannot open %s\n", argv[1]);
return 1;
}
// - malloc question about this very next line
struct dirent *b;
while (( b = readdir(a)) != NULL){
printf("%s %lu\n", b->d_name, b->d_ino);
}
int closing = closedir(a);
printf("in closing, status is %d\n", closing);
return 0;
}
Newcomer to C, clueless too - please be gentle! :)