gpt4 book ai didi

C 调用 chdir 后损坏的双链表

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:39 24 4
gpt4 key购买 nike

我一直在编写一些 C 代码来提供类似于 shell 的功能。到目前为止,它可以运行大多数命令,如 cat、ls、ls | grep ...等写了实现“cd”、“pwd”、“pushd”、“popd”等功能的代码后,一直在测试。如果我写“cd ..”或“cd anydir”,它将运行“chdir(anydir)”并返回到我的脚本命令提示符。在“cd”后输入任何命令后,都会返回错误:

*** Error in `./smshv4': corrupted double-linked list: 0x00000000018d5190 ***

我在一个不相关的变量中重新分配内存时隔离了这个要打印的错误。我评论了错误产生的行:

char * next_cmd(char *prompt, FILE *fp){
fprintf(stderr,"in next_cmd\n");

char *buf ;
int bufspace = 0;
int pos = 0;
int c;

printf("%s", prompt);
while( ( c = getc(fp)) != EOF ) {

if( pos+1 >= bufspace ){
if ( bufspace == 0 ){
buf = emalloc(BUFSIZ); //Error occurs while calling this function
} else {
buf = erealloc(buf,bufspace+BUFSIZ);
}
bufspace += BUFSIZ;
}

/* end of command? */
if ( c == '\n' )
break;

/* no, add to buffer */
buf[pos++] = c;
}

if ( c == EOF && pos == 0 )
return NULL;
buf[pos] = '\0';
return buf;
}

此错误仅在我使用 chdir 运行任何函数后发生。以下是我在输入 cd 时如何调用 chdir 的示例:

if(strcmp(cmdStruct.commandTemp[0],"cd") == 0){
if(cmdStruct.commandTemp[1] != NULL){
if(chdir(cmdStruct.commandTemp[1]) == -1){
perror("chdir");
return -1;
}
} else {
fprintf(stderr,"cd failed. No directory given\n");
return -1;
}
}

这个 cd 命令不起作用,因为每当我运行它时,给出的错误将在我下次输入命令时显示。如果我 cd 到一个不同的目录,运行任何东西来接收错误,然后运行“pwd”(正在运行),它将显示原始目录(输入一个命令后错误似乎自行解决)。

如何解决损坏的双链表问题?谢谢。

编辑:我调用命令提示符如下所示:

while ( (cmdline = next_cmd(prompt, stdin)) != NULL ){  //command prompt function is run
//if & sign detected, fork. otherwise run command as usual
if(hasBackgroundSign(cmdline) == 1){
pid = fork();
if(pid == 0){
if ( (arglist = splitline(cmdline)) != NULL ){
result = execute(arglist);
freelist(arglist);
}
free(cmdline);
kill(getpid(), SIGKILL);
} else {
printf("%d\n",pid);
}
} else {
//if no & sign detected, run command as usual without forking
if ( (arglist = splitline(cmdline)) != NULL ){
result = execute(arglist); //execute function contains the chdir calls
freelist(arglist);
}
free(cmdline);
}
}

最佳答案

通过使用 Valgrind 查找损坏的内存位置来解决。 Valgrind 调用了“大小为 8 的无效写入”。解决这个问题后,问题就消失了。感谢 Leon 在上面提出这个建议。

关于C 调用 chdir 后损坏的双链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37708726/

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