【问题标题】:write data to specific memory address issue将数据写入特定内存地址问题
【发布时间】:2015-11-19 12:02:50
【问题描述】:

当我使用以下代码在内存中的特定地址写入数据时,我收到一条错误消息,告诉我

“函数写入的参数1中的类型错误”。

据我所知,S_LEN 是指向0x1814 的指针,因此它应该以正确的方式工作,但在这种情况下,我得到了之前的错误。

当我通过 write(&S_LEN,0); 替换命令 write(S_LEN,0); 时,它工作正常。尽管在第一种情况下,我将十六进制数字转换传递给指向整数的指针。

谁能解释一下这个问题?

#define RAM_START 0x1800
#define S_LEN  (((int32_t *)(RAM_START))[0xFF])
    int32_t write(int32_t *dest_ptr, int32_t src)
    {                                     
        *dest_ptr = src;
         return 0;
    } 

    main()
    {
     write(S_LEN,0);
    }

【问题讨论】:

  • 为什么不使用mmap()进行内存分配?
  • 除非您有充分的理由,否则请不要将问题标记为 C 和 C++。这很可能是一个 C 问题,C++ 的答案会有很大差异,因为他们建议用更好的东西替换宏,而这在 C 中是不可能的。

标签: c pointers


【解决方案1】:

你的write函数期望int32_t *作为第一个参数,它是一个指针,所以如果你想要S_LEN,你应该使用类似的东西成为一个指针:

#define S_LEN  (((int32_t *)(RAM_START))+0xFF)

您的表达式计算结果为 int32_t,因为您将 下标运算符 [] 应用于 int32_t *(这是一个指针)。

另一方面,&S_LEN 被接受,因为它会生成您通过应用[] 获得的int32_t 的地址。

还要注意S_LEN 与内存位置4*0xFF+0x1800 相关,即0x1BFC。 (在0x1800之后是255int32_ts)。

【讨论】:

    【解决方案2】:

    在您的代码中,S_LEN 执行以下操作:

    1. 它将RAM_START 转换为int32_t * 类型的指针
    2. int32_t * 类型指针的订阅应该是 int32_t 数字

    但是write需要第一个参数是int32_t *类型,所以&S_LEN是对的,因为S_LEN返回的int32_t的地址是int32_t *类型

    OSX 10.11 的输出:

    [oxnz@rmbp:tmp:0]$ cc     a.c   -o a
    a.c:14:8: warning: incompatible integer to pointer conversion passing 'int32_t'
          (aka 'int') to parameter of type 'int32_t *' (aka 'int *'); take the
          address with & [-Wint-conversion]
            write(S_LEN,0);
                  ^~~~~
                  &(   )
    a.c:5:16: note: expanded from macro 'S_LEN'
    #define S_LEN  (((int32_t *)(RAM_START))[0xFF])
                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    a.c:6:24: note: passing argument to parameter 'dest_ptr' here
    int32_t write(int32_t *dest_ptr, int32_t src)
                           ^
    1 warning generated.
    
    [oxnz@rmbp:tmp:0]$ cat a.c
    #include <stdio.h>
    #include <stdlib.h>
    
    #define RAM_START 0x1800
    #define S_LEN  (((int32_t *)(RAM_START))[0xFF])
    int32_t write(int32_t *dest_ptr, int32_t src)
    {
        *dest_ptr = src;
        return 0;
    }
    
    int main()
    {
        write(S_LEN,0);
    }
    

    【讨论】:

    • 感谢您的回复。但是,write 函数的第一个参数是指向 int32 的指针
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-15
    • 2013-12-31
    • 2017-06-16
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    相关资源
    最近更新 更多