调用free()方法后出现分段错误,但只有某些值



我有这个简单的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_ptrn", 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_ptrn");
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) --> %dn", int_ptr, *int_ptr);
printf("t[-] freeing char_ptr's heap memory...n");
free(char_ptr);
printf("t[+] allocating another 17 bytes for char_ptrn");
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 memoryn");
free(char_ptr);
printf("Program exitingn");
return 0;
}

当我用参数大于或等于29运行它时,一切都ok..但如果我放置28或更少,它会出现分割故障…我正在考虑堆和堆栈之间的地址问题,问题发生在free() int_ptr调用。有人能帮我吗?我不明白这有什么意义…

谢谢大家祝你有个愉快的一天

您复制到char_ptr内存("This memory is in the heap segment")的第一个字符串是35字节长,包括终止NUL字节。这将破坏堆中小于35的所有参数。

只是碰巧它可以为您工作到29,因为free可能不依赖于覆盖的数据

相关内容

  • 没有找到相关文章

最新更新