【问题标题】:debugging c using heap memory [closed]使用堆内存调试c [关闭]
【发布时间】:2014-01-21 03:50:46
【问题描述】:

我正在使用堆内存,我在下面写了一个示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){
  FILE *fd;

  //Alocate memory on the heap;
  char *UserInput = malloc(20);
  char *OutputFile = malloc(20);

  if(argc < 2){
    printf("Usage: %s <string to be written to /tmp/notes>\n", argv[0]);
    exit(0);
  }

  //Copy data into the heap memory
  strcpy(OutputFile, "/tmp/notes");
  strcpy(UserInput, argv[1]);

  //Print out some debug messages
  printf("___DEBUG___\n");
  printf("[*] UserInput @ %p: %s\n", UserInput, UserInput);
  printf("[*] OutputFile @ %p: %s\n", OutputFile, OutputFile);
  printf("[*] Distance between: %ld\n", UserInput - OutputFile);
  printf("_________________\n\n");

  //Writing the data out to the file
  printf("Writing to \"%s\" to the end of %s...\n", UserInput, OutputFile);
  fd = fopen(OutputFile, "a");
  if (fd == NULL){
    fprintf(stderr, "Error openning %s\n", OutputFile);
    exit(1);
  }

  fprintf(fd, "%s\n", UserInput);
  fclose(fd);

  return 0;
}

我执行的是:./heap test 输出是:

___DEBUG___
[*] UserInput @ 0x1a13010: test
[*] OutputFile @ 0x1a13030: /tmp/notes
[*] Distance between: -32
_________________

我认为“距离” \\ 出现了问题 argv[1] int 类型的最大长度是整数的“31”\\ char 类型中argv[1] 的最大长度为“58”个字符\\ 例如:

 ./heap 123...01 => 31 integers
 ./heap qqq..qqq => 58 characters

之后我面临一个打开的错误... 为什么 -32 发生在距离之间?

【问题讨论】:

  • UserInput 完全是多余的。
  • 另外,您期望输出是什么?这两个指针不指向同一个数组,所以无论你得到什么结果都是没有意义的(它会让你的代码调用未定义的行为)。
  • 这个问题似乎是题外话,因为它是无稽之谈。
  • 这是一个堆溢出的练习......所以之间的距离必须告诉实际的距离......
  • 这里如何定义 UserInput 变量?

标签: c linux debugging heap-memory


【解决方案1】:

Malloc 从不为后续请求分配连续内存。 这取决于当前可用内存的情况。

作为一种良好的编程习惯,请在程序存在之前释放两个 malloc 分配,即在 return 0 语句之前。

free(OutputFile);
free(UserInput);
return 0;

【讨论】:

  • @MortezaLSC - 我已编辑您的代码以在程序退出之前释放所有 malloc 分配。
  • 谢谢,但它不起作用...谢谢 :)
【解决方案2】:

这里没有错。指针由 malloc() 函数分配,该函数可以并且确实为指针分配相当任意的值。正常的 malloc() 实现将保留几个字节来标记分配缓冲区的长度,并利用空闲列表上现有的缓冲区大小。因此,如果您分配两个缓冲区,就像您所做的那样,没有什么说它们在堆空间中必须是连续的。事实上,他们不会。

我不知道您在这里要做什么,但是两个 malloc() 指针之间的“距离”永远不会是缓冲区的确切长度。

【讨论】:

  • 谢谢。但是,我怎样才能理解我可以在我的程序的 argv[1] 中给出多少字节?我认为“-32”发生了错误
  • 注意:这是一个使用堆内存的缓冲区溢出练习 :) 谢谢你在高级
  • 这是一个模棱两可的问题。如果要限制输入 UserInput 的字符数,请使用 strncpy() 函数。如果要获取所有字符,则使用 strlen(argv[1]) 查找长度并将 malloc UserInput 设置为适当的大小(不要忘记最后的 null )。或者你可以直接打印 argv[1],然后完全跳过 UserInput。
  • 我想通过字节数的限制溢出它。但是“之间的距离”应该告诉我有多少字节是正常的,如果我使用超过它,程序必须崩溃......但是“-32”对我来说很奇怪..另一台机器上的这个程序告诉“24”之间的距离。如果我使用 25 个字节,程序会告诉 Open Error...
  • 距离为:地址(0x1a13010)和地址(0x1a13030)之间的距离
猜你喜欢
  • 2011-06-13
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多