首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C程序上4个字节指针地址的奇异性

C程序上4个字节指针地址的奇异性
EN

Stack Overflow用户
提问于 2020-01-01 16:39:18
回答 1查看 140关注 0票数 0

在程序的一部分中,我以两种不同的方式打印出了相同的指针。

代码语言:javascript
复制
vpx_codec_iface_t *ptr = vpx_codec_vp9_cx();
printf("ptr1 %p\n", ptr);
printf("ptr2 %p\n", vpx_codec_vp9_cx());

奇怪的是,这导致了以下输出。

代码语言:javascript
复制
ptr1 FFFFFFFFDAF9CED0
ptr2 00000000DAF9CED0

我可以通过添加一些代码或添加一些换行符来“修复”错误。

代码语言:javascript
复制
int x = 0;
vpx_codec_iface_t *ptr = vpx_codec_vp9_cx();
printf("ptr1 %p\n", ptr);
printf("ptr2 %p\n", vpx_codec_vp9_cx());
printf("x=%d\n", x);

这将导致以下输出。

代码语言:javascript
复制
ptr1 0000000066A7CED0
ptr2 0000000066A7CED0
x=0

是什么导致了这种行为?我在Windows 10上使用VisualStudio2019编译器,为x64编译。函数调用vpx_codec_vp9_cx()是在来自libvpx项目的vpxmd.lib中实现的。

编辑:我仍然在浏览你的答案和评论,但我在下面创建了一个最小的例子。不幸的是,它涉及到构建整个vpx库,所以我需要一些时间来简化这个部分。

代码语言:javascript
复制
#include <stdio.h>
#include "vpx/vpx_encoder.h"

int main(int argc, char **argv) {
  printf("This is main\n");
  vpx_codec_iface_t *ptr = vpx_codec_vp9_cx();
  int x = 0;
  printf("ptr1 %p\n", ptr);
  printf("ptr2 %p\n", vpx_codec_vp9_cx());
  printf("x=%d\n", x);
  exit(0);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-01 17:07:30

在编译环境中是否打开了警告?这看起来非常像是缺少了vpx_code_vp9_cx()的原型。在第一种情况下,向ptr分配时,预期的类型强制将扩展(默认) int值vpx_codex_vp9_cs()。在第二种情况下,printf将保持原样。一个简单的例子可以用: print.c:

代码语言:javascript
复制
#include <stdio.h>
int main() {
    void *x = myptr();
    printf("x = %p\n", x);
    printf("myptr() = %p\n", myptr());
    return 0;
}

myptr.c:

代码语言:javascript
复制
int myptr(void) {
    return 0xd0000020;
}

注意,print.c没有myptr()的声明。在我的系统中,一个朴素的编译:CCprint.cmyptr.c -o p生成:

代码语言:javascript
复制
print.c:6:12: warning: implicit declaration of function 'myptr' is invalid in C99
      [-Wimplicit-function-declaration]
        void *x = myptr();
                  ^
print.c:6:8: warning: incompatible integer to pointer conversion initializing
      'void *' with an expression of type 'int' [-Wint-conversion]
        void *x = myptr();
              ^   ~~~~~~~
print.c:8:27: warning: format specifies type 'void *' but the argument has type
      'int' [-Wformat]
        printf("myptr() = %p\n", myptr());
                          ~~     ^~~~~~~
                          %d
3 warnings generated.

我的编译器显然是冗长的,但关键是,过去30年的每个编译器都应该报告某种诊断,至少在忽略之前,您应该了解这些诊断。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59554230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档