I am working on a project that involves multi-threading. Although I have a decent understanding of multi-threading, I have not written many such codes. The following code is just a simple code that I wrote for hands-on. It works fine when compiled with gcc -pthread.

To build upon this code, I need to include some libraries that already have pthread included and linked. If I compile by including and linking those libraries, 3 out of 5 times it gives segmentation fault. There is some problem with the first *for*-loop in main() -- replacing this *for*-loop with multiple statements does the work.

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

#define NUM_THREADS 3

pthread_mutex_t m_lock = PTHREAD_MUTEX_INITIALIZER;

typedef struct{
    int id;
    char ip[20];
} thread_data;

void *doOperation(void* ctx)
{
    pthread_mutex_lock(&m_lock);
    thread_data *m_ctx = (thread_data *)ctx;
    printf("Reached here\n");
    pthread_mutex_unlock(&m_lock);
    pthread_exit(NULL);
}

int main()
{
    thread_data ctx[NUM_THREADS];
    pthread_t threads[NUM_THREADS];

    for (int i = 0; i < NUM_THREADS; ++i)
    {
        char ip_n[] = "127.0.0.";
        char ip_h[4];
        sprintf(ip_h, "%d", i+1);
        strcpy(ctx[i].ip, strcat(ip_n, ip_h));
    }

    for (int i = 0; i < NUM_THREADS; ++i)
    {
        pthread_create(&threads[i], NULL, doOperation, (void *)&ctx[i]) 
    }

    for (int i = 0; i < NUM_THREADS; ++i)
    {
        pthread_join(threads[i], NULL);
    }

    pthread_exit(NULL);

}

```