首页 > 解决方案 > 我如何知道 C 程序进程的数据、堆栈和堆的起始地址以及它们在内存中的大小?

问题描述

我如何知道linux中C程序进程的数据,堆栈和堆的起始地址及其在内存中的大小?

标签: clinuxprocessstackdynamic-memory-allocation

解决方案


我已经包含了几个代码片段来展示如何确定存储在堆和堆栈上的数据的起始地址和大小。我建议您查看下面的链接以更好地理解这些示例。如果您还有其他问题,请告诉我。

栈和堆的区别

C 程序的内存布局

了解程序的内存

int main() {
    // The following variables are stored on the stack
    int i = 4;
    char c = 'a';
    char s[6] = "Hello";

    // Starting addresses (use & operator)
    printf("Starting address of i = %p\n", &i);
    printf("Starting address of c = %p\n", &c);
    printf("Starting address of s = %p\n", s);

    // Sizes
    printf("Size of i = %ld\n", sizeof(int));
    printf("Size of c = %ld\n", sizeof(char));
    printf("Size of s = %ld\n", sizeof(char) * 6); // 5 characters and a null character
}

int main() {
    /* The following variables are pointers (i.e., they store addresses).
     * The addresses they hold are locations in the heap.
     * The size of the location pointed to by the pointer is 
       determined by the data type (int, char, etc.) */
    int *i = malloc(sizeof(int));
    char *c = malloc(sizeof(char));
    char *s = malloc(sizeof(char) * 6);

    // Place value(s) in the create memory locations
    *i = 4;
    *c = 'c';
    strcpy(s, "Hello");

    // Starting addresses (each variable i,c,s is an address)
    printf("Starting address of i = %p\n", i);
    printf("Starting address of c = %p\n", c);
    printf("Starting address of s = %p\n", s);

    // Sizes
    printf("Size of i = %ld\n", sizeof(int));
    printf("Size of c = %ld\n", sizeof(char));
    printf("Size of s = %ld\n", sizeof(char) * 6); // 5 characters and a null character
}

推荐阅读