Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "*((char*)-1) = 'x';" code mean?

I had a problem in reading redis source code, can anyone tell me what is the use of the last statement in the _redisAssert function in debug.c:

*((char*)-1) = 'x';
like image 666
dereky Avatar asked Dec 30 '13 18:12

dereky


1 Answers

Update

I found the line in debug.c mentioned in the OP and we can see from two lines above this code:

redisLog(REDIS_WARNING,"(forcing SIGSEGV to print the bug report.)");

and the same code can be found in _redisPanic as well, so it looks like their way to force a SIGSEGV when an assertion fails or there is a panic.

Original

This looks like a debugging tool, we can see from this document Redis debugging guide and relevant section says:

Redis has a command to simulate a segmentation fault (in other words a bad crash) using the DEBUG SEGFAULT command (don't use it against a real production instance of course ;). So I'll use this command to crash my instance to show what happens in the GDB side:

and shows this gdb output:

 (gdb) continue
 Continuing.

 Program received signal EXC_BAD_ACCESS, Could not access memory.
 Reason: KERN_INVALID_ADDRESS at address: 0xffffffffffffffff
 debugCommand (c=0x7ffc32005000) at debug.c:220
 220         *((char*)-1) = 'x';
             ^^^^^^^^^^^^^^^^^^^

What it is doing is casting -1 to a *char ** and then performing indirection on it and assigning 'x' to that memory location. As the thread that alk linked Is ((void *) -1) a valid address? says on most systems it will not be valid to access, let alone assign a value to. This will generate a segmentation fault on most modern operating systems.

This is undefined behavior and as was went over in the thread What is the simplest standard conform way to produce a Segfault in C? it can not be relied on. Compilers are getting smarter and there are some famous examples where the compiler is smart about exploiting undefined behavior in unexpected and bad ways.

like image 123
Shafik Yaghmour Avatar answered Sep 25 '22 14:09

Shafik Yaghmour