【发布时间】:2021-04-21 15:09:19
【问题描述】:
这是我正在阅读的书中的一个示例,用于演示堆内存的使用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *char_ptr;
int *int_ptr;
int mem_size;
if (argc < 2) //if not given an argument, defaukt memory size is 50//
mem_size = 50;
else
mem_size = atoi(argv[1]);
printf("\t[+] allocating %d bytes of memory on the heap for char_ptr\n", mem_size); //memory is given, and passed to char pointer//
char_ptr = (char *)malloc(mem_size);
if(char_ptr == NULL) { //check for error//
fprintf(stderr, "Error: could not allocate memory.\n");
exit(-1);
}
strcpy(char_ptr, "This memory is located on the heap.");
printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
printf("\t[+] allocating 12 bytes of memory on the heap for int_ptr\n");
int_ptr = (int *)malloc(12);
if(int_ptr == NULL) {
fprintf(stderr, "Error: coud not allocate heap memory.\n");
exit(-1);
}
*int_ptr = 31337;
printf("int_ptr (%p) --> %d\n", int_ptr, *int_ptr);
printf("\t[-] freeing char_ptr's heap memory...\n");
free(char_ptr);
printf("\t[+] allocating another 15 bytes for char_ptr\n");
char_ptr = (char *)malloc(15);
if(char_ptr == NULL) {
fprintf(stderr, "Error: coud not allocate heap memory.\n");
exit(-1);
}
strcpy(char_ptr, "new memory");
printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);
printf("\t[-] freeing int_ptr's heap memor...\n");
free(int_ptr);
}
我对这条线感到困惑:strcpy(char_ptr, "This memory is located on the heap.");
char_ptr 已经包含分配的堆内存的地址,那么这个文本是如何复制到指针中的呢?从printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);来看,分配的堆内存的地址似乎也没有改变。这是否基本上意味着指针包含两个值?这是如何工作的?
kingvon@KingVon:~/Desktop/asm$ ./a.out
[+] allocating 50 bytes of memory on the heap for char_ptr char_ptr (0x55ef60d796b0) --> 'This memory is located on the heap.'
[+] allocating 12 bytes of memory on the heap for int_ptr int_ptr (0x55ef60d796f0) --> 31337
[-] freeing char_ptr's heap memory...
[+] allocating another 15 bytes for char_ptr char_ptr (0x55ef60d79710) --> 'new memory'
[-] freeing int_ptr's heap memor...
[-] freeing char_ptr's heap memory...
【问题讨论】: