“*((char*)-1) = 'x';"是什么意思?代码是什么意思? [英] What does "*((char*)-1) = 'x';" code mean?

查看:49
本文介绍了“*((char*)-1) = 'x';"是什么意思?代码是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在阅读redis源代码时遇到了问题,谁能告诉我debug.c_redisAssert函数中最后一条语句的用途是什么:>

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

推荐答案

更新

我在 debug.c 在 OP 中提到,我们可以从这段代码上面的两行看到:

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.)");

并且在 _redisPanic 中也可以找到相同的代码,因此当断言失败或出现恐慌时,它们看起来像是强制 SIGSEGV 的方式.

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.

原创

这看起来像一个调试工具,我们可以从这个文档中看到Redis调试指南和相关部分说:

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

Redis 有一个命令可以使用 DEBUG SEGFAULT 命令模拟分段错误(换句话说,严重崩溃)(当然不要将它用于实际生产实例;).因此,我将使用此命令使我的实例崩溃以显示 GDB 端发生的情况:

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:

并显示此 gdb 输出:

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

它正在做的是将 -1 转换为 *char **,然后对其执行间接寻址并将 'x' 分配给该内存位置.作为 alk 链接的线程 ((void *) -1) 是有效地址吗? 表示在大多数系统上访问是无效的,更不用说为其分配值了.这将在大多数现代操作系统上生成分段错误.

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.

这是未定义的行为,并且在线程最简单的标准符合方式是什么在 C 中产生段错误? 不能依赖它.编译器变得越来越聪明,并且有一些著名的例子,其中 编译器很聪明地利用未定义的行为出乎意料和糟糕的方式.

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.

这篇关于“*((char*)-1) = 'x';"是什么意思?代码是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆