ctime(& rawtime)擦除malloc'ed字符数组?

时间:2012-09-22 02:57:00

标签: c unix memory-management

我真的不知道这里发生了什么,但这是我的解释>

我malloc用于保存文件名数组的字符串数组,没问题。然后我进入一个while循环,它保持所有正确的值,直到它打到它打印时间

time(&rawtime);
printf("It is now: %s\n\n",ctime(&rawtime)); 

然后我的价值观消失了。无法在任何地方找到它们,我好像现在有一个空数组。

以下是代码的其余部分

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

  int i,j, directSize,start=0,flag=0, menu;
  size_t size;
  char path[1024];  //current working directory path
  char ** files;    //created to store the directory contents in an array of strings
  char buffer ;     //buffer holds menu selection
  time_t rawtime;


  //buffer = (char*) malloc(sizeof(char));
  files = (char**) malloc(sizeof(char*)+1);

  //allocating memory for strings
  for(i=0;i<50;i++)
  {
    files[i] =(char*) malloc(64*sizeof(char));
  }

  getcwd(path,size);

  pid_t child;
  DIR * d;
  struct dirent *de;

  d = opendir(".");

  i=0;

  while((de = readdir(d)))
  {
    files[i] = de->d_name;
    i++;
  }


  directSize = i;
  closedir(d);

  printf("file[0]: %s",files[0]);

  while(flag == 0)
  {
    printf("\nfiles[0]: %s\n",files[0]);    //works 

    printf("Current Working directory: %s\n", path);
    printf("\nfiles[0]: %s\nSize: %d\n",files[0],directSize);   //works

    time(&rawtime);
    printf("It is now: %s\n\n",ctime(&rawtime)); //problem area? 

    printf("files[0]: %s\nSize: %d\n",files[0],directSize);     //doesn't work
    printf("Files:\t\t0. (..)\n");

    for(i=start;i<start+4;i++)
      printf("\t\t%d. %s \n",i+1, files[i]);

    //formatted print for the command menu 
    printf("\nOperation:\tV View\n\t\tR Run\n\t\tP Previous Files\tN Next Files\n\t\tX Exit\t\t\tH Help\n");

    printf("\nCommand: ");
    scanf("%c", &buffer);
    getchar();
    //if(isalpha(buffer))
    //  strcpy(buffer,toupper(buffer));
    printf("command chosen is: %c\n",buffer);

    //if(buffer != "N" && buffer != "P" && buffer != "X")
    //{
    //  printf("File/Directory #: ");
    //  scanf("%d", &menu);
    //}

    if(buffer == 'E' || buffer == 'e')
      flag=flag+ 1; 

  }


  return 0;
}

1 个答案:

答案 0 :(得分:1)

问题是你没有字符串的深层副本。

 while((de = readdir(d)))
  {
    files[i] = de->d_name;   /* you just made files[i] pointing to de->d_name, instead of
                              * copy the content to files[i].
                              */
    i++;
  }

所以在closedir()之后,libc将重用内部缓冲区,内容可能被libc的其他函数修改,然后你得到一个垃圾内容。用{{替换它1}}。