1

I read a unit test, that checks for invalid free or double-free:

int main() {
    char *a = (char*) my_malloc(200);
    char *b = (char*) my_malloc(50);
    char *c = (char*) my_malloc(200);
    char *p = (char*) my_malloc(3000);

    (void) a, (void) c;

    memcpy(p, b - 200, 450);
    my_free(p + 200);
    printstatistics();
}

Why do we need to cast char* to void and what happens in memory when we do this cast?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Anatoly
  • 1,908
  • 4
  • 25
  • 47
  • 3
    Those casts on a & c are totally unnecessary, as are the statements they represent. I suspect they are there to silence the compiler's "unused" warnings, not for any legitimate reason. – Lee Daniel Crocker Apr 10 '15 at 19:35
  • The other casts for the return of `my_malloc` are probably completely useless. Good chances are that this returns `void*`, so you shouldn't and mustn't cast them. – Jens Gustedt Apr 10 '15 at 21:43

1 Answers1

6
(void) a, (void) c;

is a common way to get rid of compiler warnings about unused variables. Since those two variables are initialised only and not used later, most compilers would issue warnings about it. Since this is apparently some kind of a test of memory allocation they are not used on purpose, so someone decided to silence warnings.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51