1
  • 操作系统:Windows Vista(x86)
  • 编译器:代码::块

我目前正在编写一个打开指定目录并读取其内容的程序。而不是在找到文件名后立即使用 printf() 显示文件名。我将它们保存在内存中并稍后显示它们。我使用以下 if 语句来触发内存重新分配。我还包括了相关变量的声明。

//Represents what the new index will be after the current file name is added
//to 'stack.ptr'
#define NEW_INDEX (stack.index+(strlen(ptr_dirent->d_name)))

//Contains the pointer that points to the directory's contents 'stack.ptr',
//the size of 'stack.ptr' which is 'stack.size', and the current index
//'stack.index'
struct stack
{
  int index;
  char *ptr;
  int size;
};struct stack stack;

//Sets the index to 0 and allocates 256 bytes of memory for 'stack.ptr'
stack.index = 0; stack.size = 256;
stack.ptr = malloc(sizeof(char)*stack.size);

if(NEW_INDEX > stack.size)
{
  char *temp; stack.size *= 2;
  temp = realloc(stack.ptr, sizeof(char)*stack.size);
  if (temp == NULL)
  {
    printf("ERROR: %i Bytes of memory could not be allocated.\n", stack.size);
    free(stack.ptr); closedir(dirp); return '\000';
  }
  else {stack.ptr = temp;}
}

该程序运行良好,直到我将“stack.size”(这是数组大小)的初始值设置为 2 而不是 256(以便程序必须重新分配内存)。我的程序崩溃了,因为 realloc() 返回 NULL 但我有足够的可用内存。我知道 realloc() 确实工作了几次,因为“stack.size”在崩溃时为 16(每次重新分配内存时“stack.size”加倍)。我尝试将“stack.size”设置为几个不同的值,我发现将“stack.size”设置为 1 或 2 会导致崩溃,并且总是在“stack.size”达到 16 时发生。谁能向我解释一下? 我担心即使我将 'stack.size' 设置为 256,如果目录大到足以触发内存重新分配,我的程序可能会崩溃。同样在不相关的注释中,我读到了 openddir("."); 将打开当前目录,我发现它确实如此,但由于某种原因,当前目录中的所有文件并非都在 'stack.ptr' 和 . 当我将'stack.ptr'的内容输出到标准输出时,会显示和..。

4

1 回答 1

3

您没有向我们展示包含错误的行。它可能看起来像:

strcpy(stack.ptr+stack.index, ptr_dirent->d_Name);

这里的问题是strcpy()复制strlen() + 1字节。您正在编写超出分配数组末尾的终止 NUL 字符。

于 2012-12-18T20:36:43.120 回答