简体   繁体   中英

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

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:)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM