NikkiNelson NikkiNelson - 24 days ago 6
C Question

Core Dumped - Trying to print Min with Threads

I'm trying to use threads to print out the minimum number in an array I have done this in the following code for a static array:

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

int length = 5;
int nums[5] = {93, 12, 54, 72, 68};
int r_min;

void *myMin(void *param) {
int i;

r_min = nums[0];
for(i = 0; i < length; ++i) {
if(r_min > nums[i]) r_min = nums[i];
}
pthread_exit(0);
}

int main(int argc, char** argv) {
pthread_t tid;
pthread_create(&tid, 0, myMin, NULL);
pthread_join(tid, NULL);
printf("Min = %d\n", r_min);
return 0;
}


This correctly prints out "12" in my example, which is correct. I'm trying to now implement taking in numbers from the command line instead of the hard-coded array and printing out the correct response. My new code is as follows:

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

int length = 5;
int nums[5] = {93, 12, 54, 72, 68};
int r_min;

void *myMin(void *param) {
int i;

r_min = nums[0];
for(i = 0; i < length; ++i) {
if(r_min > nums[i]) r_min = nums[i];
}
pthread_exit(0);
}

void* myMin2(void *param) {
char** argv;
int i, j;
// printf("Test");
argv = param;
for(i = 0; i < length; ++i){
printf("%s\n", argv[i]);

if(i > 0){
j = atoi(argv[1]);
printf(" %d\n", j);
}
}

pthread_exit(0);
}

int main(int argc, char** argv) {
pthread_t tid;
length = argc;
pthread_create(&tid, 0, myMin2, NULL);
pthread_join(tid, NULL);
printf("Min = %d\n", r_min);
return 0;
}


I'm setting the length equal to the amount of arguments added (I can/will add a -1 there since calling the execution command counts as 1). When I call my new Min2 function I just get a segmentation fault (core dumped) and I'm not entirely sure why. I'm very new to the C language so this is all confusing stuff to me! Thanks for your assistance! :)

Answer Source

You're passing NULL as the parameter to myMin2. You need to pass argv instead.

pthread_create(&tid, 0, myMin2, argv);