Search code examples
cdynamic-memory-allocationreallocfunction-definition

How to properly access this realloc-ed array?


In this code below I am trying to create an array of ints that can be accessed from the main() function, however, Address-sanitizer gives me stack-buffer-overflow-error and I cannot figure out what I am doing wrong. What am I missing?

#include <stdlib.h>

void reallocFail(int **arrayOfInts) {
    *arrayOfInts = (int *)malloc(sizeof(int));
    for (int i = 1; i <= 10; i++) {
        *arrayOfInts = (int *)realloc(*arrayOfInts, (i) * sizeof(int));
        *arrayOfInts[i - 1] = i;
    }
}

int main(void) {
    int *arrayOfInts;
    reallocFail(&arrayOfInts);
    return 0;
}

Solution

  • There is just a simple typo in *arrayOfInts[i - 1] = i;. suffix operators such as [] bind stronger than prefix operators such as *. Hence you should write:

       (*arrayOfInts)[i - 1] = i;
    

    Note also that you should check for memory reallocation failure and you can initialize *arrayOfInts to NULL as realloc(NULL, size) is equivalent to malloc(size).

    Here is a modified version:

    #include <string.h>
    #include <stdlib.h>
    
    int reallocFail(int **pp, int n) {
        int i;
        *pp = NULL;
        for (i = 0; i < n; i++) {
            int *p = realloc(*pp, (i + 1) * sizeof(*p));
            if (p == NULL)
                break;
            p[i] = i + 1;
            *pp = p;
        }
        return i;
    }
    
    int main(void) {
        int *arrayOfInts = NULL;
        int n = reallocFail(&arrayOfInts, 10);
        for (int i = 0; i < n; i++) {
            printf("%d%c", arrayOfInts[i], " \n"[i == n-1]);
        }
        free(arrayOfInt);
        return 0;
    }