kevin
kevin

Reputation: 827

How to use 32-bit pointers in 64-bit application?

Our school's project only allows us to compile the c program into 64-bit application and they test our program for speed and memory usage. However, if I am able to use 32-bit pointers, then my program will consume much less memory than in 64-bit, also maybe it runs faster (faster to malloc?)

I am wondering if I can use 32-bit pointers in 64-bit applications?

Thanks for the help

Upvotes: 10

Views: 14636

Answers (2)

Morpfh
Morpfh

Reputation: 4093

Using GCC?

The -mx32 option sets int, long, and pointer types to 32 bits, and generates code for the x86-64 architecture. (Intel 386 and AMD x86-64 Options):

Then benchmark :)

Upvotes: 41

Lie Ryan
Lie Ryan

Reputation: 64923

You could "roll you own". The following may reduce memory usage -- marginally -- but it may not improve speed as you'd have to translate your short pointer to absolute pointer, and that adds overhead, also you lose most of the benefits of typechecking.

It would look something like this:

typedef unsigned short ptr;
...

// pre-allocate all memory you'd ever need
char* offset = malloc(256); // make sure this size is less than max unsigned int

// these "pointers" are 16-bit short integer, assuming sizeof(int) == 4
ptr var1 = 0, var2 = 4, var3 = 8;

// how to read and write to those "pointer", you can hide these with macros
*((int*) &offset[var1]) = ((int) 1) << 16;
printf("%i", *((int*) &offset[var1]));

with a bit more tricks, you can invent your own brk() to help allocating the memory from the offset.

Is it worth it? IMO no.

Upvotes: 2

Related Questions