0

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;
}
monk
  • 1,953
  • 3
  • 21
  • 41

1 Answers1

1

int *ret = (int *) malloc(sizeof (int)); allocates space for just one integer.

*ret = i; does not increment the pointer, it just changes the value to which it it pointing.

So ret's value is some address, where you first write 0, then 1, etc.

*(p + i) When you do this, you are dereferencing a memory, which wasn't allocated by your malloc call, it could be used for something else, or even worse could be read-only or outside process's address space, causing a crash.

I think what you want is:

int *ret = (int *) malloc(sizeof(int) * nproc);// allocating for nproc integers

And then:

ret[i] = i;

Nellie Danielyan
  • 1,001
  • 7
  • 19
  • 1
    thank you so much , you can also put same answer in the hyperlinked question. I'll accept it too as your answer really helped me :)\ – monk Apr 12 '19 at 20:53