[英]How can I know the starting address of data,stack and heap, and their sizes in memory for a C program process?
对于 linux 中的 C 程序进程,我如何知道 memory 中数据、堆栈和堆的起始地址及其大小?
我已经包含了几个代码片段来展示如何确定存储在堆和堆栈上的数据的起始地址和大小。 我建议您查看下面的链接以更好地理解这些示例。 如果您还有其他问题,请告诉我。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.