当我尝试更改某些地址值时,C 程序停止工作

标签 c memory low-level

看看我的代码:

 #include <stdio.h>
 #include <limits.h>

int main (int argc, const char *argv[]) {

typedef unsigned char byte;

byte *pointer;
byte b1=1;
byte b2=2;
int i1 =4;
int i2 =0x12345678;
byte b3=5;
byte b4=6;
byte b5=7;
byte b6=9;

//pointer = &b6;
pointer = (byte*)&i2;
printf("pointer  has value %p\n", pointer);
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
*pointer = 255;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
*pointer = 45;
printf("the byte it points to contains %x\n", *pointer);
pointer =  pointer + 1;
*pointer = 34;

printf("the byte it points to contains %x\n", *pointer);
//printf("How big is int in this machine? %d\n", INT_MAX);
//insert code here ...
printf (" b1 (%p) = %x\n", &b1, b1);
printf (" b2 (%p) = %x\n", &b2, b2);
printf (" i1 (%p) = %d\n", &i1, i1);
printf (" i2 (%p) = %x\n", &i2, i2);
printf (" b3 (%p) = %x\n", &b3, b3);
printf (" b4 (%p) = %x\n", &b4, b4);
printf (" b5 (%p) = %x\n", &b5, b5);
printf (" b6 (%p) = %x\n", &b6, b6);

return 0;
}

*pointer = 255; ,可能是第 40 行,编译器崩溃,或者代码停止工作,说这个 if I make , *pointer = 255 or *pointer = 254

and if I set any other values except this , my program works well i.e. *pointer = 4556 or *pointer = 45

或者在任何其他任意值的情况下,它运行时不会有任何打击。请告诉我有关地址的这种行为的信息。

资料来源:Richard Buckland 教授,由于他的指导,我正在探索所有这些。

最佳答案

编译器与此无关。您正在尝试取消引用并分配给一个无效的指针,即您不拥有的内存

只做++pointer; *pointer = <value>;是危险的 pointer指向 int 类型的单个值,所以++pointer (或添加除零之外的任何数字)正在将指针移动到您可能无权写入甚至访问的某个内存位置。因此出现了错误。

关于当我尝试更改某些地址值时,C 程序停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39794101/

相关文章:

python - 如何在c中扩展python?

c - 在 gcc 中编译 c 时收到有关强制转换 "from pointer to integer of different size"的警告

c - Lua中为什么使用索引方法而不是特殊方法

debugging - Visual Studio 在调试时是否显示虚拟地址或物理地址?

c - 如何在一次内存操作中加载可能的最大整数?

C、写系统调用,写int

c - 私有(private)变量与减少 OMP

java - 加载不需要的 Java 类

c++ - 在另一个进程的内存中搜索字符串的每次出现

c - Windows 内核驱动程序 : ZwAllocateVirtualMemory causing thread to terminate