Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

c - 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';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...