logoalt Hacker News

dmitrygrtoday at 12:14 AM2 repliesview on HN

FYI, at least in C/C++, the compiler is free to throw away assignments to any memory pointed to by a pointer if said pointer is about to be passed to free(), so depending on how you did this, no perf impact could have been because your compiler removed the assignment. This will even affect a call to memset()

see here: https://godbolt.org/z/rMa8MbYox


Replies

kentonvtoday at 3:13 AM

I patched the free() implementation itself, not the code that calls free().

I did, of course, test it, and anyway we now run into the "freed memory" pattern regularly when debugging (yes including optimized builds), so it's definitely working.

shaknatoday at 12:25 AM

However, if you recast to volatile, the compiler will keep it:

    #include <stdlib.h>
    #include <string.h>

    void free(void* ptr);
    void not_free(void* ptr);


    void test_with_free(char* ptr) {
        ptr[5] = 6;
        void *(* volatile memset_v)(void *s, int c, size_t n) = memset;
        memset_v(ptr + 2, 3, 4);
        free(ptr);
    }

    void test_with_other_func(char* ptr) {
        ptr[5] = 6;
        void *(* volatile memset_v)(void *s, int c, size_t n) = memset;
        memset_v(ptr + 2, 3, 4);
        not_free(ptr);
    }
show 2 replies