0

I am getting compilation error when I am checking if an address is 64 byte aligned or not.

error: invalid operands to binary expression ('void *' and 'int')

  #define BYTE_ALIGNMENT 64
  void *is_mem_aligned(void* ptr){

    if(ptr%BYTE_ALIGNMENT == 0){
          printf("already aligned %p\n",ptr);
          return ptr;

    }

}
user968000
  • 1,765
  • 3
  • 22
  • 31

1 Answers1

5

You can't perform arithmetic (except addition and subtraction, but they have special meaning) on pointers because they're not numbers. If the C implementation you're working on defines uintptr_t, you can cast them to uintptr_t and perform arithmetic on numbers that "should" in some sense match the addressing model. So:

if((uintptr_t)ptr % BYTE_ALIGNMENT == 0){

Aside from this, alignment is not testable. A declared object of a given type is suitably aligned for its type, and memory obtained by malloc is suitable for any type not overaligned via _Alignas. Then, if p is aligned mod N, (char*)p+k*N is aligned for any integer k for which the sum is defined. Your program logic has to preserve alignment where needed if you do anything funny; you can't test it.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711