请问C标准允许自修改code? [英] Does the C Standard Allow for Self-Modifying Code?

查看:155
本文介绍了请问C标准允许自修改code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在在C移植的方式是自修改code可能吗?

Is self-modifying code possible in a portable manner in C?

我想问的原因是,在某种程度上,OOP依靠自我修改code(因为code,它执行在运行时实际数据,例如,在一个v表生成) ,然而,似乎是,如果这是采取的太多,这将prevent最优化中的编译器。

The reason I ask is that, in a way, OOP relies on self-modifying code (because the code that executes at run-time is actually generated as data, e.g. in a v-table), and yet, it seems that, if this is taken too far, it would prevent most optimizations in a compiler.

例如:

void add(char *restrict p, char *restrict pAddend, int len)
{
    for (int i = 0; i < len; i++)
        p[i] += *pAddend;
}

这是优化编译器可能会扯起 * pAddend 圈外的,因为它不会与 P 干扰。然而,的此不再自修改code进行有效的优化

An optimizing compiler could hoist the *pAddend out of the loop, because it wouldn't interfere with p. However, this is no longer a valid optimization in self-modifying code.

在这种方式,似乎C没有允许自修改code,但在同一时间,那不是意味着你不能用C做一些喜欢的事情OOP?难道真的Ç支持自修改code?

In this way, it seems that C doesn't allow for self-modifying code, but at the same time, wouldn't that imply that you can't do some things like OOP in C? Does C really support self-modifying code?

推荐答案

自修改code是不可能用C的原因很多,其中最重要的是:

Self-modifying code is not possible in C for many reasons, the most important of which are:


  1. 由编译器生成的code是完全由编译器,可能不会是什么样子程序员试图写入code,它修改自身期望什么。这是一个的基本的问题做SMC在所有的,不只是一个便携的问题。

  2. 功能和数据的指针是完全独立的用C;语言没有提供方法来回它们之间的转换。这个问题不是根本,因为一些实现或更高级别的标准(POSIX)保证code和数据指针共享一个重新presentation。

  1. The code generated by the compiler is completely up to the compiler, and might not look anything like what the programmer trying to write code that modifies itself expects. This is a fundamental problem with doing SMC at all, not just a portability problem.
  2. Function and data pointers are completely separate in C; the language provides no way to convert back and forth between them. This issue is not fundamental, since some implementations or higher-level standards (POSIX) guarantee that code and data pointers share a representation.

除此之外,自修改code是只是一个非常非常糟糕的主意。 20年前,它可能有一些应用,但现在它会导致什么,但错误,残暴的性能和便携故障。请注意,在某些国际检索单位,指令缓存是否甚至认为这是对缓存code可能做出不指定/ UN predictable的变化!

Aside from that, self-modifying code is just a really really bad idea. 20 years ago it might have had some uses, but nowadays it will result in nothing but bugs, atrocious performance, and portability failures. Note that on some ISAs, whether the instruction cache even sees changes that were made to cached code might be unspecified/unpredictable!

最后,虚函数表有什么做自修改code。这是纯粹的修改功能的问题的指针的,这是数据,而不是code。

Finally, vtables have nothing to do with self-modifying code. It's purely a matter of modifying function pointers, which are data, not code.

这篇关于请问C标准允许自修改code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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