天天看点

C程序的存储布局——代码段

Code:

  1. #include<stdio.h>  
  2. int f(int a,int b)    
  3. {  
  4.   return a+b;     
  5. }  
  6. int main()  
  7. {  
  8.   int(*p)(int ,int );    
  9.   void *q;          
  10.   p=f;             
  11.   q=(void *)p;      
  12.   printf("the code is : 0x%x", *((int *)q));  
  13.   *((int *)q)=0x12345678;       
  14.   return 0;  
  15. }  

打印的是函数f中的语句“return a+b"

Code:

  1. $ ./motify_code  
  2. the code is : 0x8be58955  
  3. Segmentation fault  

修改正文段时报错可知:linux环境下的正文段是受操作系统写保护的。

补充:函数的代码存储在代码段中。

继续阅读