Please review for any unnecessary casting, memory leaks, wrong use of pthread call, or validation problems in the given code.
/**********************************************************************
* FILENAME :thread_1.c
* DESCRIPTION:Contains Code for a program that demonstrates the
* use of pthread calls.The created threads will accept an
* argument and return the argument after adding a number.
****************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *thread_entry(void *arg)
{
int *p;
p=(int*)arg;
*p = (*p) + 10;
pthread_exit(p);
}
int main(int argc, char* argv[])
{
pthread_t* threads;
int t,ret,numthreads = 0,thread_success = 0,*iptr;
void* thread_result;
if ( argc < 2 )
{
printf("Less number of Args -Pl. enter a valid number of threads to be created\n");
exit(1);
}
numthreads = atoi(argv[1]);
if ( 0 > numthreads )
{
printf("Pl. enter a valid number of threads to be created\n");
exit(1);
}
threads = calloc(numthreads, sizeof(pthread_t));
if (NULL == threads)
{
printf("Failed to alocate memory in malloc\n");
exit(1);
}
/*Creating the Threads*/
for(t=0; t < numthreads; t++)
{
printf("Creating Thread\n");
iptr = (int*)malloc(sizeof(int));
*iptr = t;
ret = pthread_create(&threads[t],NULL,thread_entry,(void*)iptr);
if(ret )
{
printf("Printf Error Creating Thread");
free(iptr);
}
else
{
thread_success++;
}
}
//Now waiting for all the threads
//thread_success is the number of successfully created threads
for(t=0; t < thread_success; t++)
{
ret = pthread_join(threads[t],&thread_result);
if (ret)
{
printf("Error joining a thread");
}
else
{
printf("Joined thread returned %d\n", *((int*)thread_result));
free(thread_result);
}
}
free(threads);
return 0;
}