Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: exception

...

Code Block
bgColor#ccccff
langc
#include <assert.h>
#include <stdint.h>
 
void h(void) {
  intptr_t i = (intptr_t)(void *)&i;
  uintptr_t j = (uintptr_t)(void *)&j;
 
  void *ip = (void *)i;
  void *jp = (void *)j;
 
  assert(ip == &i);
  assert(jp == &j);
}

INT36-C-EX3:

An integer may be converted to a void* and back as long as the pointer is not dereferenced, and the integer is in range (that is, the appropriate range for an intptr_t or uintptr_t).

The following POSIX code passes an integer, cast as a void* to a thread, and the thread prints the integer.

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <pthread.h>


void *print_int(void *ptr) {
  intptr_t i = (intptr_t) ptr;
  printf("The number is %jd\n", i);
  return NULL;
}

int main(void) {
  pthread_t thr1;
  intptr_t i = 123;
  int result;

   if ((result = pthread_create(&thr1, NULL, print_int, (void *)i)) != 0) {
    /* Handle error */
  }

  pthread_exit(NULL);
  return 0;
}

Risk Assessment

Converting from pointer to integer or vice versa results in code that is not portable and may create unexpected pointers to invalid memory locations.

...