cast to pointer from integer of different size, pthread code

You are wrongly using an hack to pass an integer to a thread. The idea behind what you are doing is an integer is 4 bytes and a pointer is 4 bytes in x86_32 (8 bytes in x86_64) so I can convert an integer type to a pointer type and then convert it back to an int type without losing any data. This works in the majority of the scenarios, but there is not guarantee that a pointer and an integer have the same size. The C standard does not specify this.

The compiler returns a warning because you are converting an int to void * which may have different size, ( but in fact in your machine they have the same size).

There is a error in you code, when you convert the int to a void* calling the pthead_create function, you should convert it back to an integer type. So, this line is wrong :

int *id=(int *)s;

it should be :

int id = (int)s; 

Consider this example where the argument for the thread function is zero.

s=0; therefore  ---> *id=(int*)0; // Null pointer 

This is a pointer to the address zero. When you try to deference it, you will likely get an segmentation fault.

The best way to do this is by using the intptr_t type. This type has the same size of a pointer (not int) in every architecture. It is defined as follows :

Integer type capable of holding a value converted from a void pointer and then be converted back to that type with a value that compares equal to the original pointer.

So you can do something like this:

#include <stdint.h>

void *threadfunc(void *param)
{
    int id = (intptr_t) param;
    ...
}

int i, r;
r = pthread_create(&thread, NULL, threadfunc, (void *) (intptr_t) i);

(This example code has been taken from : How to cast an integer to void pointer?)

However, there is not guarantee that the size of int is the same of the size of intptr_t, but it’s really unlikely that some data is lost in the conversion process.

EDIT

Additional errors :

  • float **Aa, **Bb, **Cc; are not initialised.
  • start and end exceeds the limit of the array. The matrix rows are not allocated in consecutive memory areas.
  • if the thread function is working on a chunks of the matrix, there is not point to go through all the values of the matrix A and B. You might want only the internal loop which, in theory, should work on the part of matrix assigned to it.

I would consider to rewrite the code for the matrix multiplication because the algorithm is wrong.

Leave a Comment