Search code examples
cloopsrandommalloccalloc

(C) malloc corrupted top size with random numbers


So I'm trying to get an array of random 8-bit numbers of size count but I get the corrupted top size error whenever count is larger than 6. I read that it should be related to memory assignment but I can't figure out what is wrong exactly. I'm new to C so I'm not sure if the pointers are written correctly.

int *randBytes(int count) {

    srand(time(0));
    int *num = calloc(count, sizeof(uint8_t));

    for (int i = 0; i < count; i++) {
        num[i] = (rand() % 255) + 1;
    }

    return num;
};

int main() {
    int randLen = 120;
    int *nums = randBytes(randLen);
    for (int i = 0; i < randLen; i++) {
        printf("%d ", nums[i]);
    }
}

Solution

  • int *num = calloc(count, sizeof(uint8_t));
    

    You are allocating a buffer of size count * 1 == count. If sizeof(int) == 4 then the array can contain count / 4 ints.

    for (int i = 0; i < count; i++) {
        num[i] = (rand() % 255) + 1;
    }
    

    You are then treating the array as an array of count ints, not count / 4 ints.


    You can fix this by either changing your calloc:

    int *num = calloc(count, sizeof(*num));
    

    or your for loop:

    for (int i = 0; i < count / sizeof(int); i++) {
        num[i] = (rand() % 255) + 1;
    }