【发布时间】: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