zoukankan      html  css  js  c++  java
  • c语言内存

    程序由指令和数据组成。

    c语言中内存分为5个区,由高地址到低地址分别为栈、堆、全局区(静态区)、常量区和代码区。

    栈区(stack):存放函数局部变量,函数的参数值和返回值,由系统自动管理。

    堆区(heap):由malloc函数分配内存再由free释放内存。

    全局区(静态区):存放全局变量和静态变量(static),初始化的全局变量和静态变量存放在(.data),没有初始化的全局变量和没有初始化的静态变量存放在(.bss)区。

    常量区:字符串常量"hello world"(当一个字符串常量用来为数组初始化的时候,给字符串不会放在常量区,而是放在对应的数组中)和被const修饰的全局变量

    存放在(.rodata段)。

    代码区:存放函数的二进制代码(text)。如果某一段内存分配为代码区,那这块区域可读不可写。

    生长方向:栈由高地址向低地址方向生长,堆由低地址向高地址方向生长。

    int main(){    
        char a[]="hello world";     
        printf("
    the a address is 0x%p,%s",a,a);    
        a[3]='a';
        printf("
    the a address is 0x%p,%s",a,a);
        return 0;
    }

    数组 "hello world"存于栈中,所以它的值可以修改。

    int main(){    
        char *a="hello world";     
        printf("
    the a address is 0x%p,%s",a,a);    
        a[3]='a';
        printf("
    the a address is 0x%p,%s",a,a);
        return 0;
    }

    "hello world"存于常量区,指针a存于栈中。a指向"hello world"的首地址,由于“hello world"为常量所以不能被修改。

    char c[]="hello world"; 
    int main(){    
        printf("
    the c address is 0x%p,%s",c,c);
        c[3]='a';
        printf("
    the c address is 0x%p,%s",c,c);
        return 0;
    }

    数组c存放于全局区(静态区),所以数组的值可以被修改。

    char *c="hello world"; 
    int main(){    
        printf("
    the c address is 0x%p,%s",c,c);
        c[3]='a';
        printf("
    the c address is 0x%p,%s",c,c);
        return 0;
    }

    "hello world"存在于常量区,而指针c存在于全局区(静态区):常量不可以被修改。

    int main(){    
        char a[]="hello world"; 
        char c[]="hello world"; 
        char *p ="hello world"; 
        char *d ="hello world"; 
        printf("
    the a address is 0x%p,%s",a,a);
        printf("
    the c address is 0x%p,%s",c,c);
        printf("
    the p address is 0x%p,%s",p,p);
        printf("
    the d address is 0x%p,%s",d,d);
        return 0;
    }

    上面的程序说明在常量区只保留一份相同的数据。

  • 相关阅读:
    C# 操作ACCESS数据库
    装饰模式(Decorator Pattern)
    桥接模式(Bridge Pattern)
    单件模式(Singleton Pattern)
    横竖不能重复的9个数,,,,,
    C#操作Access数据库的例子
    组合模式(Composite Pattern)
    建造者模式(Builder Pattern)
    工厂方法模式(Factory Method)
    外观模式(Façade Pattern)
  • 原文地址:https://www.cnblogs.com/ligei/p/11364784.html
Copyright © 2011-2022 走看看