[Tfug] Need help with a C++ algorithm

Stephen Hooper stephen.hooper at gmail.com
Thu Mar 15 01:58:12 MST 2007


On 3/15/07, Stephen Hooper <stephen.hooper at gmail.com> wrote:
> On 3/15/07, Brian Murphy <murphy+tfug at email.arizona.edu> wrote:
> > Quoting Jude Nelson <judecn at gmail.com>:
> > > Is there a way to determine the size of an allocated block of memory if only
> > > a pointer to it is known?
> >
> >
> > No, there is not.
> >
>
> Hate to disagree with you there dude, but yes there is:
>
> #include <stdio.h>
> #include <stdlib.h>
>
> int main(int argc,char **argv) {
>
> char *start,*seek;
> char *start2;
> int i;
>
>         if(argc < 2)
>                 return EXIT_FAILURE;
>
>         start = malloc(strtol(argv[1],NULL,16) * sizeof(char));
>         seek = start;
>         seek -= 4;
>         for(;seek != start; seek++)
>                 printf("%X %02X\n",seek,*seek & 0xFF);
>
>         start2 = malloc(1 * sizeof(char));
>         printf("next alloc starts at %X (%X difference)\n",start2,start2 - start);
>
>         free(start); // How do you think this magic works...
>         free(start2);
>
>         return EXIT_SUCCESS;
> }
>
> It is horribly system specific, but quite fun.  For a 64 bit machine
> you would obviously want to change the "seek -=", and be sure to read
> things on Linux.
>
> Run this like:
>
> allocsize 0x3F7F

Crap... don't!  Run it like:

allocsize 3F7F

I knew I shouldn't have been so sloppy.
>
> You may be surprised by the results, but an understanding of the
> processor will tell you why it allocates the low order bytes as it
> does.
>




More information about the tfug mailing list