Search code examples
ccalloc

Callocing memory


I'm trying to create a file system and I need to calloc the file descriptors.

Let's say I have two structures with the following definitions:

#define DESCRIPTOR_MAX (256)
#define TABLE_MAX (32)

typedef struct S16FS S16FS_t;

typedef struct {
    bitmap_t *fd_status;
    size_t fd_pos[DESCRIPTOR_MAX];
    inode_ptr_t fd_inode[DESCRIPTOR_MAX];
} fd_table_t;

struct FS {
    back_store_t *bs;
    fd_table_t fd_table;
};

I'm callocing a new file system with no problem:

FS_t *fs = (FS_t *)calloc(8, sizeof(FS_t));

but my problem arrises when I want to calloc the fd_table within the FS struct. Here's what I'm trying.

This one produces no errors:

fs->fd_table = *(fd_table_t*)calloc(TABLE_MAX, sizeof(fd_table_t));

I'm getting an error with the following:

fs->fd_table.fd_pos = (size_t *)calloc(TABLE_MAX, sizeof(size_t));

error: array type 'size_t [256]' is not assignable

Can someone explain to me what i'm doing wrong or if I'm just completely wrong in my process? Do I even need to calloc the fd_pos?


Solution

  • It looks like fs->fd_table.fd_pos is an array, not a pointer. If you want a dynamic array, then change the type to size_t*.

    Otherwise, it's perfectly fine to leave it as an array and not use dynamic allocation. In that case, if you want to zero the memory (as calloc does), you can just use memset:

    memset( fs->fd_table.fd_pos, 0, sizeof(fs->fd_table.fd_pos) );
    

    Oh yes, and also WhozCraig points out that your first example is a leak (allocating memory, then dereferencing and copying, followed by losing the pointer). In fact, you don't need to memset as I suggested above because the entire structure was zeroed with the first calloc.