访问用C特定内存地址 [英] Accessing Specific Memory Locations in C

查看:134
本文介绍了访问用C特定内存地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在汇编语言,我们有像

Movl AX, [1000]

这允许我们访问特定内存位置。

which allows us to access specific memory locations.

但在C我们可以做一些类似的?

But in C can we do something similar to this?

我当然知道使用内联汇编code ASM()将允许你这样做。

Of course I know inline assembly code using asm() will allow you to do this.

不过,我想了解一些C特定的技术来实现这一目标。

But I would like to know about some C specific technique to achieve this.

我尝试以下code和得到的分割误差

I tried the following code and got segmentation error

int *ptr=0xFE1DB124; 

为存储位置是由下面给出的code认定这又是混乱的,

This again was confusing as the memory location was identified by the code given below,

int var;
printf("\nThe Address is %x",&var);

因此​​,存储位置是可用的,但还是我得到分段错误。

So the memory location is available, but still I am getting segmentation fault.

感谢您提前为您的时间和耐心。

Thank You in advance for Your time and patience.

推荐答案

通用的C编译器将允许您从一个整数集的指针,并与访问内存,和他们会给你预期的结果。然而,这是一个扩展超出了C标准,所以你应该检查你的编译器文档,以确保它支持它。此功能不寻常内核code,必须在特定地址访问内存使用。它一般是不会在用户程序中非常有用。

Common C compilers will allow you to set a pointer from an integer and to access memory with that, and they will give you the expected results. However, this is an extension beyond the C standard, so you should check your compiler documentation to ensure it supports it. This feature is not uncommonly used in kernel code that must access memory at specific addresses. It is generally not useful in user programs.

正如评论所说,你可能有一个问题是,你的操作系统加载程序到一个随机位置,每一个程序加载时间。因此,你会发现在一个运行中的地址不会在另一个运行使用的地址。此外,更改源代码并重新编译可能会产生不同的地址。

As comments have mentioned, one problem you may be having is that your operating system loads programs into a randomized location each time a program is loaded. Therefore, the address you discover on one run will not be the address used in another run. Also, changing the source and recompiling may yield different addresses.

要证明你可以用一个指针来访问一个地址指定的数值,可以检索地址和一个执行程序中使用它:

To demonstrate that you can use a pointer to access an address specified numerically, you can retrieve the address and use it within a single program execution:

#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>


int main(void)
{
    //  Create an int.
    int x = 0;

    //  Find its address.
    char buf[100];
    sprintf(buf, "%" PRIuPTR, (uintptr_t) &x);
    printf("The address of x is %s.\n", buf);

    //  Read the address.
    uintptr_t u;
    sscanf(buf, "%" SCNuPTR, &u);

    //  Convert the integer value to an address.
    int *p = (int *) u;

    //  Modify the int through the new pointer.
    *p = 123;

    //  Display the int.
    printf("x = %d\n", x);

    return 0;
}

显然,这不是一个正常的程序有用它只是一个演示。只有当你有特殊需要访问特定的地址,你会用这样的行为。

Obviously, this is not useful in a normal program; it is just a demonstration. You would use this sort of behavior only when you have a special need to access certain addresses.

这篇关于访问用C特定内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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