Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an array cast as void*

I create an array:

unsigned short* array = malloc(sizeof(unsigned short)*N);

Assign values to it:

for(i=0; i<N; i++){
    array[i] = rand()%USHRT_MAX;
}

Cast it to a void* and pass it to a worker thread which will find the max value in the array:

pthread_create(&threads[0], NULL, findMax, (void*)&array);

Which looks like this:

void* findMax(void* arg){
    int i = 0;
    unsigned short max = 0;
    unsigned short* table = (unsigned short*)arg;
    for(i=0;i<N;i++){
        if(table[i]> max){
            max = table[i];
        }
    }
    printf("Max: %d\n", max);
}

The issue is that the numbers assigned in the array are misformatted. For example with the N randomly generated numbers: 3664 50980 37495 12215 33721, this loop will interpret the numbers as following instead:

table[0] = 28680
table[1] = 2506
table[2] = 5
table[3] = 0
table[4] = 32736

With the 5 and 0 as recurring pattern on the 2nd and 3rd place in the array.

I'm clearly overstepping some memory boundries, what is happening here and how do I fix it?

like image 271
Eiron Avatar asked Dec 17 '22 22:12

Eiron


1 Answers

Change:

(void*)&array

to this:

(void*)array

since void* findMax(void* arg) expects a pointer, and you were passing the address of the pointer.

like image 164
Jose Avatar answered Jan 07 '23 03:01

Jose