Memory profiling and tracking fails.



  • Hello,
    it's not quite related to Qt, but mostly in embeded and memory profiling question. I am recently trying to track a memory allocs, and writing a custom header info followed an example however my code fails:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct {
        size_t size;
    } Hdr;
    
    void* mmalloc(size_t sz)
    {
        size_t tot_size = sz + sizeof(Hdr);
        void* p = malloc(tot_size);
        ((Hdr*) p)->size = sz;
        return p + sizeof(Hdr);
    }
    
    int main(int argc, char *argv[])
    {
        int* i = (int*) mmalloc(1000 * sizeof(int));
        Hdr* h = (Hdr*) (i - sizeof(Hdr));
        printf("%d is size\n", h->size);
        return 0;
    }
    

    It's quite self-explainatory, the printf is supposed to print a size, however it always prints 0. Well I put it that way:

    Hdr* h = (Hdr*) (i - 2);
    

    it prints the correct size - 4000 in that case of 1000 int sized array. So why is this?



  • Hi,
    thats the magic of pointers in c :)

    Adding 1 to a pointer to int let the pointer be increased by the size of an int. The sizeof(..) gives you the size in bytes of the requested type. So, in your code the line

    Hdr* h = (Hdr*) (i - sizeof(Hdr));
    

    is faulty.
    Try this:

    Hdr* h = (Hdr*)(i - sizeof(Hdr)/sizeof(int));
    

    --Well I put it that way:
    --Hdr* h = (Hdr*) (i - 2);
    --it prints the correct size - 4000 in that case of 1000 int sized array.
    --So why is this?
    Because on your machine the sizeof(size_t) is 2*sizeof(int)

    gerd



  • @Gerd
    Stylish answer. Thanks. This is indeed the reason.

    regards


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.