没有malloc的指针

奋斗学习者
#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

返回值

成功时,readdir()返回指向差值结构的指针。(此结构可能是静态分配的;请勿尝试对其进行分配free(3)。)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章