0

I am attempting to create a dynamic char array (vector) in c with dynamic length/size.

Here is my attempt:

#include <stdio.h>
#include <stdlib.h>

void push_back(char **arr, char *element, int *counter) {
    if (*counter > 0) {
        arr = realloc(arr, *counter * sizeof(char *));
    }
    arr[*counter] = element;
    (*counter)++;
}

int main() {
    char **arr = malloc(1 * sizeof(char *));
    int counter = 0;

    push_back(arr, "element", &counter);
    push_back(arr, "element2", &counter);
    push_back(arr, "element3", &counter);
    push_back(arr, "element4", &counter);
    push_back(arr, "element5", &counter);
    push_back(arr, "element6", &counter);

    for (int i=0; i<counter; i++) {
        printf("%s <-\n", (char *)arr[i]);
    }

    free(arr[i]);
    return 0;
}

I receive the following error from stdout:

realloc(): invalid next size
Aborted

What am I doing wrong?

2
  • 2
    ericlippert.com/2014/03/05/how-to-debug-small-programs Commented Jul 21, 2020 at 18:19
  • 1
    You have allocated enough room in the array for *counter strings, and then you store a string in the element indexed by *counter. This is beyond the end! Commented Jul 21, 2020 at 18:39

1 Answer 1

2

you need triple pointer *** (wrrrr.....) or just return realloced pointer back.

char ** push_back(char **arr, char *element, int *counter) {
    *counter += 1;

    arr = realloc(arr, *counter * sizeof(char *));
    arr[*counter - 1] = element;
    return arr;
}

int main() {
    char **arr = NULL;
    int counter = 0;

    arr = push_back(arr, "element", &counter);
    arr = push_back(arr, "element2", &counter);
    arr = push_back(arr, "element3", &counter);
    arr = push_back(arr, "element4", &counter);
    arr = push_back(arr, "element5", &counter);
    arr = push_back(arr, "element6", &counter);

    for (int i=0; i<counter; i++) {
        printf("%s %d <-\n", arr[i], counter);
    }

    free(arr);
    return 0;
}

You do not need to malloc and then check the value of the counter. https://godbolt.org/z/xnaxKo

PS Yuo shiuld always check the result of the malloc (and friends).

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.