Question

As part of a program for a class, I have to print the output a specific way, split up into blocks of sixteen bytes. I've been searching for quite a while for a way to cast the pointer to an int or another way to perform a modulus or division remainder operation on the pointer address stored in a variable. I've hit a roadblock, does anyone here know how I could perform this seemingly simple operation? Here's the basic form of the function:

void printAddress(char *loc, char *minLoc, char *maxLoc) {
    minLoc = (loc - (loc % 16));
    maxLoc = minLoc + 16;
    printf("%p - %p - %p", minLoc, loc, maxLoc);
}

I removed all my attempts at casting it to make it clear what I'm trying to do.

Was it helpful?

Solution

The type you're looking for is uintptr_t, defined in <stdint.h>. It is an unsigned integer type big enough to hold any pointer to data. The formats are in <inttypes.h>. They allow you to format the code correctly. When you include <intttypes.h>, it is not necessary to include <stdint.h> too. I chose 16 assuming you have a 64-bit processor; you can use 8 if you're working with a 32-bit processor.

void printAddress(char *loc)
{
    uintptr_t absLoc = (uintptr_t)loc;
    uintptr_t minLoc = absLoc - (absLoc % 16);
    uintptr_t maxLoc = minLoc + 16;
    printf("0x%16" PRIXPTR " - 0x%16" PRIXPTR " - 0x%16" PRIXPTR "\n",
           minLoc, absLoc, maxLoc);
}

You could also write:

    uintptr_t minLoc = absLoc & ~(uintptr_t)0x0F;

See also Solve the memory alignment in C interview question that stumped me.

Note that there might, theoretically, be a system where uintptr_t is not defined; I know of no system where it cannot actually be supported (but I don't know all systems).

OTHER TIPS

I might not fully understood the problem, but for me it looks as if you are trying to do the good old hexdump?

void hexdump(char *buf, int size)
{
    int i;

    for (i = 0; i < size; i++)
    {
        if (i % 16 == 0)
        {
            puts("");
            printf("%p", &buf[i]);
        }

        printf("%02x ", buff[i]);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top