Search code examples
cmallocdynamic-memory-allocationrealloc

Realloc inside function doesn't work as expected


I am working on a program and I successfully isolated the non-working part, but I can't figure out why this does not work. The realloc inside the function shold reallocate the array elements but sometimes the addresses are the same and sometimes they are just 0, which causes errors inside the code and crashes

int main() {
    char *string = (char*) malloc(sizeof(char));
    resizeString(&string);
    free(string)
    return 0;
}

void resizeString(char* *string) {
    int q;
    *string = realloc(*string, 5 * sizeof(char));
    for (q = 0; q < 5; q++) {
        printf("0x%p ", &*string[q]);
    }
    printf("\n");
}

this is the result of the printf inside the for loop


Solution

  • You need to add parentheses to print the addresses of the array elements properly.

            printf("%p ", &(*string)[q]);
    

    This correctly prints consecutive addresses:

    0x6000013dc040 0x6000013dc041 0x6000013dc042 0x6000013dc043 0x6000013dc044 
    

    This has nothing to do with realloc(), you'd have the same problem if you allocated 5 characters originally.

    There's also no need to write 0x in the format string; most C libraries show that prefix automatically as part of %p format.