简体   繁体   English

什么是“*((char *) - 1)='x';”代码是什么意思?

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

我在阅读redis源代码时遇到问题,有人能告诉我_redisAssert函数中最后一个语句的_redisAssert什么

*((char*)-1) = 'x';

Update 更新

I found the line in debug.c mentioned in the OP and we can see from two lines above this code: 我在OP中提到的debug.c中找到了这行,我们可以从这段代码上面的两行看到:

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. 并且在_redisPanic也可以找到相同的代码,因此当断言失败或出现恐慌时,它看起来像是强制SIGSEGV的方式。

Original 原版的

This looks like a debugging tool, we can see from this document Redis debugging guide and relevant section says: 这看起来像一个调试工具,我们可以从这个文件中看到Redis调试指南和相关部分说:

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 ;). Redis有一个使用DEBUG SEGFAULT命令模拟分段错误(换句话说是一个糟糕的崩溃)的命令(当然不要将它用于真实的生产实例;)。 So I'll use this command to crash my instance to show what happens in the GDB side: 所以我将使用此命令来崩溃我的实例以显示GDB端发生的事情:

and shows this gdb output: 并显示此gdb输出:

 (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. 它正在做的是将-1转换为* char **,然后对其执行间接操作并将'x'分配给该内存位置。 As the thread that alk linked Is ((void *) -1) a valid address? 作为alk链接的线程是((void *)-1)一个有效的地址? 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? 这是未定义的行为 ,因为在线程中已经过去了什么是在C中生成Segfault的最简单的标准符合方式? 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. 编译器变得越来越聪明,并且有一些着名的例子, 编译器很聪明地以意外和坏的方式利用未定义的行为

In your expression *((char*)-1) = 'x'; 在你的表达式中*((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. 您将值-1char * ,它为您提供指向负地址的指针,然后您尝试将值'x'分配给此地址的内容,这绝对会给出分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM