Creating an array to hold posix thread ids: Only dynamic array works

I am facing a strange error while creating posix threads:
Given below are two snippets of code, the first one works whereas the second one gives a garbage value in the output.

Snippet 1
This works:
--------------
int *threadids;
threadids = (int *) malloc (num_threads * sizeof(int));

for(i = 0; i<num_threads; i++)
threadids [i]= i;

for(i=0; i<num_threads; i++)
pthread_create(&threads[i], NULL, pthread_init, &threadids[i]);

.
.
void *pthread_init(void threadid)
{
int tid;
tid = (int)(
(int *)threadid));
printf("Thread id is %d", tid);
pthread_exit(NULL);
}

Output: Thread id is 0
--------------

Snippet 2
This doesn't work:
--------------
int threadids[num_threads];
for(i = 0; i<num_threads; i++)
threadids [i]= i;
.
.
.
Output: Thread id is 634800
--------------

As you can see, the only difference is in the way the array threadids is declared. But the second snippet gives a garbage value.

I will be glad if someone points out whats going wrong with the first snippet. Thanks.

Where is this code called from?
I guess from some function.
In this case first example works fine becuase dynamically allocated threadids exists beyond this fucntion, but it second example it dies immediately.
Remember, pthread_create doesn't wait for actual start-up of new thread.

I am not sure I understand. But you were right, if the above code is placed in the main() function, it works fine, but if I place it in a separate function and call this function from main(), it gives the garbage output.

But I am still not quite sure why it shouldn't work. As you said, first example works fine becuase dynamically allocated threadids exists beyond this fucntion, but it second example it dies immediately. So, shouldnt I face a problem when I place the code directly in the main() function ?? The threadids could die immediately again before the thread is actually spawned, in which case it picks up a garbage output.

Thanks.

It depends on operating system. In case of Solaris your new thread might not even start before your application ends up.
The basic idea is that pointer your pass to pthread_create must eixsts at the moment you thread starts-up. And if you plan to use this data in this thread (otherwise why do you pass it?) you must guarantee that this data is not being destroyed while your thread is running. Usually people use prthread_join for this purpose.

I get it.

Thanks a lot for your help. -- Kshitij