gpt4 book ai didi

ctime(&rawtime) 删除 malloc 的字符数组?

转载 作者:行者123 更新时间:2023-11-30 15:55:05 25 4
gpt4 key购买 nike

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

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

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

然后我的值(value)观就消失了。在任何地方都找不到它们,我现在似乎有一个空数组。

这是其余的代码

#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;
}

最佳答案

问题是您没有对字符串进行深层复制。

 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的其他函数修改,然后您收到了垃圾内容。请将其替换为 strcpy(files[i], de->d_name)

关于ctime(&rawtime) 删除 malloc 的字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12540313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com