我在 C 语言中有一个简单的小程序,我发布了它的代码:
#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) {
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);
char_ptr = (char *) malloc(mem_size);
if(char_ptr == NULL) {
fprintf(stderr, "Error: could not allocate heap memory.\n");
exit(-1);
}
strcpy(char_ptr, "This memory is in the heap segment");
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: could 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 17 bytes for char_ptr\n");
char_ptr = (char *) malloc(17);
if(char_ptr == NULL){
fprintf(stderr, "Error: could 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 memory.\n");
free(int_ptr);
printf("\t[-] freeing char_ptr's memory\n");
free(char_ptr);
printf("Program exiting\n");
return 0;
}
当我使用大于或等于 29 的参数运行它时,一切正常..但是如果我放置 28 或更少,则会出现分段错误...我在考虑堆和堆栈之间的地址问题,问题发生在free() int_ptr 调用。谁能帮我?我无法理解这有任何意义...
非常感谢大家 有美好的一天