This is continuation of This question , I have been trying to implement the advice given there . I am somehow able to print the value within the function but not able to print it in the caller function(main).
I am getting following output: The problem is that printf
inside print_affinity
function is proper and later returned to main. but when I am trying to print the pointer value its showing incorrect values. I am guessing this is because pointer is already incremented inside the print_affinity
function.
How can I print the correct value in the caller function ?
sched_getcpu = 3
sched_getaffinity =
*ret is 0 //correct
*ret is 1 //correct
*ret is 2 //correct
*ret is 3 //correct
*(p + 0) : 3
*(p + 1) : 0
*(p + 2) : 0
*(p + 3) : 0
code:
#define _GNU_SOURCE
#include <assert.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int * print_affinity() {
cpu_set_t mask;
long nproc, i;
int enabled_core,j;
int *ret = (int *) malloc(sizeof (int));
if (sched_getaffinity(0, sizeof(cpu_set_t), &mask) == -1) {
perror("sched_getaffinity");
assert(false);
} else {
nproc = sysconf(_SC_NPROCESSORS_ONLN);
printf("sched_getaffinity = ");
for (i = 0; i < nproc; i++) {
enabled_core = CPU_ISSET(i, &mask);
if ( enabled_core == 1 )
{
*ret = i;
printf("*ret is %d\n",*ret); //correct output
}
}
}
return ret;
}
int main(void) {
cpu_set_t mask;
long nproc;
int *p , i;
printf("sched_getcpu = %d\n", sched_getcpu());
nproc = sysconf(_SC_NPROCESSORS_ONLN);
p=print_affinity();
for ( i = 0; i <nproc ; i++ ) {
printf( "*(p + %d) : %d \n", i, *(p + i)); //incorrect output
//printf( "*(p + %d) : %d \n", i-nproc, *(p -nporc + 1)); //incorrect output
}
free(p);
return EXIT_SUCCESS;
}