3

I'm trying to store a list of every mount point on a Linux system in a string array with C. I'm focused on this piece of code.

int i = 0;
char **mountslist = malloc(1024 * sizeof(char *));

/*
 * Make sure that the number entries in the array are less than the allocated
 * 1024 in the absurd case that the system has that many mount points.
 */
while (i < 1024 && (ent = getmntent(mounts))) {
    /*
     * The output of getmntent(mounts) goes down to
     * the next mount point every time it is called.
     */
    mountslist[i] = strdup(ent->mnt_dir);
    i++;
}

I was wondering how I could dynamically allocate the number of entries in the mountslist array (currently statically set at 1024) to avoid that limit and wasting memory. If I had the final value of i when declaring mountslist I could use char *mountslist[i]; or char **mountslist = malloc(i * sizeof(char *));

7
  • you can do your second thing - malloc(i *.... The first one is a non standard c extension (variable length array) Commented Aug 29, 2018 at 1:16
  • 3
    Look up realloc. Commented Aug 29, 2018 at 1:18
  • 4k (or 8k on 64-bit systems) ain't gonna break the bank. I'd say you've already wasted enough time here. But you should learn about realloc if you're going to code in C. Commented Aug 29, 2018 at 1:27
  • @rici I agree that what I have here is probably pointless and the code I have now is fine, I just posted it as I couldn't find an answer so that now there will be one for other people in a similar situation. Commented Aug 29, 2018 at 1:28
  • 1
    It's only 1024 times sizeof(char *). You could simply realloc (downwards) afterwards. Commented Aug 29, 2018 at 1:28

1 Answer 1

2

You can use realloc to change the size of an allocated memory block:

int i = 0;
int len = 10;
char **mountslist = malloc(len * sizeof(char *));

while ((ent = getmntent(mounts)) != NULL) {
    if (i >= len) {
        len *= 2;
        char **tmp = realloc(mountslist, len * sizeof(char *));
        if (tmp) {
            mountslist = tmp;
        }
    }
    mountslist[i] = strdup(ent->mnt_dir);
    i++;
}

As shown above, a good rule is to double the amount of space you allocate when you run out of space. That prevents excessive calls to realloc which may move the allocated memory each time.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.