0

I'm trying to reallocate an array of pointers in the following way:

void PhraseArgumentReallocator(PhraseArgument** phraseArgsList, int sizeOfArray) { 
    PhraseArgument** reallocatedPhraseArgsList = (PhraseArgument**)realloc(*phraseArgsList, (sizeof(PhraseArgument*) * (sizeOfArray + 1)) );
    if (NULL != reallocatedPhraseArgsList) {
        phraseArgsList = reallocatedPhraseArgsList;
    }
    else{
        printf("Error:memory allocation failure\n");
        exit(1);
    }
    PhraseArgument* NewphraseArgs = (PhraseArgument*)calloc(1, sizeof(PhraseArgument));
    if (NULL == NewphraseArgs) {
        printf("Error:memory allocation failure\n");
        exit(1);
    }
    InitializePhraseArgumentProps(NewphraseArgs);

    phraseArgsList[sizeOfArray] = NewphraseArgs;
}

But, when I try to print out the new element outside the function:

    PhraseArgumentReallocator(phraseArgList, *sizeOfArray);
    PhraseArgument* element = phraseArgList[*sizeOfArray];
    printf("element\n");
    printf("type=%d\n", element->Type);
    printf("ArgumentOne=%s\n", element->ArgumentOne);
    printf("ArgumentTwo=%s\n", element->ArgumentTwo);

I get an unhandled exception. What am I doing wrong here?

Mark Cohen
  • 13
  • 1
  • 2
    Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) with all missing things that are required to compile. – MikeCAT May 07 '21 at 15:42
  • It is suspicious to pass `PhraseArgument*` to `realloc` and assign its result to `PhraseArgument**`. – MikeCAT May 07 '21 at 15:43
  • Also note that casting results of `malloc()` family is [considered as a bad practice](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – MikeCAT May 07 '21 at 15:43

0 Answers0