Search code examples
carrayspthreadsmallocrealloc

Array of pthread pointers


I am trying to dynamically allocate a array of pthread pointers, but get this glibc error:

*** glibc detected *** ./test: realloc(): invalid next size: 0x00000000084d2010 ***

The code:

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

int main(int argc, char** argv) {
    pthread_t **threads;
    int i;

    for(i=1;i<100;i++) {
        threads = realloc(threads, sizeof(pthread_t*)*i);
        threads[i] = malloc(sizeof(pthread_t));
    }

   return EXIT_SUCCESS;
}

What am i doing wrong here?


Solution

    • You should initialize threads (emphasis is mine).

    C11 (n1570), § 7.22.3.5 The realloc function

    If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined.

    • sizeof(pthread_t *) * i doesn't allocate enough memory to access to thread[i]. You have to allocate ((sizeof(pthread_t *) * (i + 1)).