Reputation: 33
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.
Upvotes: 0
Views: 120
Reputation:
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?
Upvotes: 1
Reputation: 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?
Upvotes: 1
Reputation: 967
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
Upvotes: 1