0

I'm quite confused about what happens here.

while ( (ent = readdir(dir)) != NULL)
    {
        char *name = ent -> d_name;
        ....
    }

This is just some basic code for scanning a directory. Fair enough. But I can't understand how this compiles, because how in the name of... can the compiler determine the size of ent -> d_name? No one knows it at compile time, and memory MUST be allocated for that, am I right? Is the compiler automatically malloc()ing this for me or what? I'm using GCC under Ubuntu if that's relevant.

Thanks in advance.

user4520
  • 3,401
  • 1
  • 27
  • 50

2 Answers2

3
  • can the compiler determine the size of ent -> d_name?

Compiler doesn't need to.

On Linux, the dirent structure is defined as follows:

struct dirent {
    ino_t          d_ino;       /* inode number */
    off_t          d_off;       /* offset to the next dirent */
    unsigned short d_reclen;    /* length of this record */
    unsigned char  d_type;      /* type of file; not supported
                                   by all file system types */
    char           d_name[256]; /* filename */
};

After this

char *name = ent -> d_name;

name just points to first element of array ent->d_name.

  • Is the compiler automatically malloc()ing this for me or what?

Here

while ( (ent = readdir(dir)) != NULL)

readdir return a pointer to dirent structure.

This is what man says:

On success, readdir() returns a pointer to a dirent structure. (This structure may be statically allocated; do not attempt to free(3) it.)

Apparently readdir allocates memory for you.

Also read this: why does the C readdir man page say to not call free on the static allocated result struct

Community
  • 1
  • 1
kotlomoy
  • 1,420
  • 8
  • 14
1

Maybe I'm missing the obvious, but if name is a char * and ent->d_name is a char * (which they should be for correct typing), then surely all that's happening is that one pointer to a block of char (name) is being set to point to the same block of char that another pointer (ent->d_name) points to.

There is no allocation of memory going on, it would seem to me.

Neil Townsend
  • 6,024
  • 5
  • 35
  • 52