c - 使用堆内存调试c

标签 c linux debugging heap-memory

我正在使用堆内存,我写了一个例子:

#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”\\ 最大长度为argv[1] char 类型是“58”个字符\\ 例如:

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

之后我遇到了一个 Unresolved 错误...... 为什么之间的距离为-32?

最佳答案

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

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

关于c - 使用堆内存调试c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20904282/

相关文章:

c - 从核心转储中获取被调用函数的返回值

c++ - SDL Window 最小化后无法恢复

linux - 如何查看符号链接(symbolic link)的完整绝对路径

c++ - 断点在 Microsoft Visual C++ 中停止工作

c# - Visual Studio 2008 : Step to next line is very slow when debugging managed code

c - printf中的*有什么用?

c++ - gtk 最小尺寸

澄清并记住 C 中的 const 用法

linux - 恢复无限嵌套/递归 tmux session ?

c - Valgrind 是否存在已知的误报问题?