2

I was compiling this program and the compilation went fine. The moment I executed it, it failed with free(): invalid pointer error.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *p = NULL;
    if ((p = (char *) malloc((int)sizeof(char) * 100)) == NULL) {
        printf("ERROR: unable to allocate memory\n");
        return -1;
    }
    p += 50;
    free(p);    
    return 0;
}

I compiled using gcc -o memtest m.c command.

Are there any GCC compiler options that will give a warning/error/indication about these invalid pointer errors during compile time?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
  • 5
    Most deallocation errors cannot be detected statically. – James McNellis Dec 31 '11 at 06:46
  • 1
    ISO/IEC 9899:1999 §7.20.3.2 The `free` function says: _The `free` function causes the space pointed to by `ptr` [its argument] to be deallocated, that is, made available for further allocation. If `ptr` is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the `calloc`, `malloc`, or `realloc` function, or if the space has been deallocated by a call to `free` or `realloc`, the behavior is undefined._ Since `p + 50` was not returned by `malloc()`, you get undefined behaviour; a core dump is one such undefined behaviour. – Jonathan Leffler Dec 31 '11 at 08:40
  • Runtime version: http://stackoverflow.com/questions/8080046/gcc-flags-to-improve-run-time-error-catching Google "static analysis". – Ciro Santilli OurBigBook.com Jun 06 '16 at 15:01
  • [Don't cast the result of `malloc` in C](http://stackoverflow.com/q/605845/995714) – phuclv Jun 06 '16 at 15:07

3 Answers3

5

No. Use Electric Fence or Valgrind.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    Electric Fence and Valgrind are great, but also work at run time (just like the error that the OP is already getting), not compile-time. – caf Dec 31 '11 at 07:55
2

compile time no, runtime - yes: http://gcc.gnu.org/wiki/Mudflap_Pointer_Debugging

The closest you may get for compile time is: http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Dialect-Options.html

Anycorn
  • 50,217
  • 42
  • 167
  • 261
1

No, such errors aren't detected at compile-time because in practice such detection would only trigger for the most trivial cases, like your example.

caf
  • 233,326
  • 40
  • 323
  • 462