1

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?

1 Answer 1

2
  • 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)).
Sign up to request clarification or add additional context in comments.

3 Comments

I just wonder why he's reallocating the array one element larger with every iteration instead of allocating the whole thing once before the for loop.
I don't understand either. But it seems to be a code extract.
Great, thanks. This is just an example of some other code where i don't necessarily know how many times i need to realloc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.