0

We are writing a program that allocates and frees memory automatically, a garbage collector in other words. It should work in a 64-bit machine and 32-bit machine without having to go in and change the code. This means that our bitwise functions cannot have a, for example, x << 63, since this would crash in a 32 bit machine. So what we need is a constant that is set when the program is compiled and it should be either the length of pointer or an uintptr_t that will be either 4 bytes or 8 bytes long depending on the platform and use these as a starting point.

I hope my question was clear, it wasn't easy to formulate it.

alk
  • 69,737
  • 10
  • 105
  • 255
Ricardo DM
  • 33
  • 5

3 Answers3

1

Have you tried pre-processor directives? As such:

#ifdef SYSTEM_32_BITS
   int * myPtr = 0x00;
#elseif SYSTEM_64_BITS
   long myVal = 0;
#endif

You can define one system and the other parameter would not compile. Would that work out for you?

  • 1
    Note that preprocessor defines have to be identifiers and identifiers can't start with a digit, so you'd need to use some name other than `32BIT_SYSTEM` — maybe `SYSTEM_32_BITS` vs `SYSTEM_64_BITS` (which leaves open 128-bit and 16-bit systems for future expansion or historic contraction). – Jonathan Leffler Dec 30 '17 at 03:53
1

You can use sizeof to do this. E.g.:

#include <stdio.h>
#include <stdint.h>

static const size_t ptr_size = sizeof(int*);
static const size_t ptr2_size = sizeof(uintptr_t);

int main() {

    printf("int*: %zu\n", ptr_size);
    printf("uintptr_t: %zu\n", ptr2_size);

    return 0;
}

This will give you the following on a 64-bit platform:

int*: 8
uintptr_t: 8
Luke Smith
  • 893
  • 4
  • 8
1

You might want to use <stdint.h> (and its intptr_t) and <limits.h>. Both are specified by C11 standard (see n1570). You could use INTPTR_MAX (and/or INTPTR_WIDTH, the latter being specific to some implementations, like GCC), which are preprocessor constants.

You could use some build automation trick to autodetect at build time (e.g. with autoconf) if you have a 64 or a 32 bits system (so generate something with preprocessor flags), and this is very common. You could also use feature_test_macros(7).

We are writing a [...] garbage collector

Writing an efficient GC could be difficult and is time-consuming (and generally requires some compiler and operating-system specific code). Did you consider using some existing library for GC, e.g. Boehm GC or MPS?

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547