#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
我从这篇文章中学到,我需要使用malloc分配内存,因此我将其更改为如下所示,并且可以正常工作:
- struct stat *something;
+ struct stat *something = malloc(sizeof(struct stat));
在先前但相关的练习中,我没有使用malloc,并且它已经起作用。我迷路了!为什么在下面的“ * struct dirent b; ”行中不需要malloc ?
或者,换句话说,我们如何才能知道有效负载太多并使用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;
}
C的新手,也很无知-请保持温柔!:)
问题所在
struct stat *something;
stat("/etc/profile", something);
这something
是一个未初始化的指针,指向无处,这会产生未定义的行为,就像stat
在无效地址上写东西一样。当malloc
您为其分配内存并传递指向该内存位置的指针时,这stat
就是它起作用的原因。
但是您不需要为此使用malloc
,只是不必声明something
为指针:
struct stat something;
stat("/etc/profile", &something); // <-- look at the usage of &
在其中stat
,应使用&
-operator返回指向的指针something
。
在您的其他程序中
struct dirent *b;
while (( b = readdir(a)) != NULL)
readdir
返回指向有效位置的指针,该函数本身负责使用有效对象并返回指向该对象的指针。但是,您不能执行以下操作free(b)
:
返回值
成功时,
readdir()
返回指向差值结构的指针。(此结构可能是静态分配的;请勿尝试对其进行分配free(3)
。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句