简体   繁体   English

GCC 错误、错误代码或 gcc 是好的编译器

[英]GCC error, bad code or gcc is good compiler

I have this code:我有这个代码:

int *b;
b = 50;
printf("Pointer point to address: %p and also point to this value: %d", b, *b);
return 0

I got this error: main.c:6:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion]我收到此错误:main.c:6:7: 警告:赋值使指针从整数而不进行强制转换 [-Wint-conversion]
timeout: the monitored command dumped core超时:受监控的命令转储核心
sh: line 1: 47524 Segmentation fault timeout 10s main sh: line 1: 47524 Segmentation fault timeout 10s main

I wanna print value from fifty byte of memory.我想从五十字节的内存中打印值。

Is my code right or will compiler do it work.我的代码是对的还是编译器会起作用。

Assuming you are running the program on a recent OS like Linux, Mac or Windows, 50 will no be the bytes located at the address 50 in your physical memory ;假设您在 Linux、Mac 或 Windows 等最新操作系统上运行该程序,则 50 将不是位于物理内存中地址 50 处的字节; that's an address in a virtual space.那是虚拟空间中的地址。

Then your process (program) has only access to a very limited range in that virtual space, which 50 is unlikely to be from ;那么您的进程(程序)只能访问该虚拟空间中非常有限的范围,其中 50 不太可能来自; in that case the OS protects the illegal access and stops your process (segfault) ;在这种情况下,操作系统会保护非法访问并停止您的进程(段错误); anyway you could even get a result that may or may not be the correct one, this is called undefined behavior , and you better not rely in this case on a apparently working executable.无论如何,您甚至可能会得到一个可能正确也可能不正确的结果,这称为未定义行为,在这种情况下,您最好不要依赖明显有效的可执行文件。

To access directly the physical memory, you either need to build a kernel module, or boot from a DOS-like OS, for instance.例如,要直接访问物理内存,您需要构建内核模块,或者从类似 DOS 的操作系统启动。

main.c:6:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion] main.c:6:7: 警告:赋值使指针从整数而不进行强制转换 [-Wint-conversion]

This being said, you need to cast 50 as a int * to clear the warning.话虽如此,您需要将50int *以清除警告。

b = (int *)50;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM