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

岁酱吖の 提交于 2020-01-09 10:52:35

问题


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';

回答1:


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.




回答2:


In your expression *((char*)-1) = 'x';:

You're casting the value -1 to char * which gives you a pointer to a negative address then your trying to assigne the value 'x' to the content of this address which absolutly gives a segmentation fault.



来源:https://stackoverflow.com/questions/20844863/what-does-char-1-x-code-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!