Reputation: 3
I am trying to get to the bottom of an issue with pthreads in C. While my second thread returns the value correctly, the first one just gives me (I assume) a memory address.
The code should do following:
Create a 2 threads which calculate the factorial and the exponential value of a given number from the console.
The Factorial is coded as a function and the exponential calculator is in the main code.
Thanks for any help!
#include <pthread.h>
#include <stdio.h>
void *fac_x(void *x_void_ptr)
{
int *x_ptr = (int *)x_void_ptr;
int counter = *x_ptr;
for (int i = 1; i < counter ; i++) {
*x_ptr *= i;
}
printf("x factorising finished\n");
return NULL;
}
int main()
{
int x,y, counter;
printf("Enter an integer: ");
scanf("%d",&x);
y = x;
counter = y;
printf("Input = %d\n",x);
pthread_t fac_x_thread;
if(pthread_create(&fac_x_thread, NULL, fac_x, &x)) {
fprintf(stderr, "Error creating thread\n");
return 1;
}
while (counter != 0) {
y *= y;
counter--;
}
if(pthread_join(fac_x_thread, NULL)) {
fprintf(stderr, "Error joining thread\n");
return 2;
}
printf("Factorial: %d \nExponential: %d\n", x, y);
return 0;
}
Upvotes: 0
Views: 69
Reputation: 32594
the first one just gives me (I assume) a memory address.
this is not an address, you (try to) compute a very great value, you have an overflow very quickly
for 3 it is already 6561 (3*3 = 9, 9*9 = 81, and finaly 81*81=6561)
for 4 the value is 2^32 too great in 32bits (4*4= 16, 16*16 = 256, 256*256 = 65536, and finally 65536*65536 = 4294967296 = 2^32)
for 5 the value is 23283064365386962890625 = 0x4EE2D6D415B85ACEF81 > 2^75 too great for 64b !
Upvotes: 2