【问题标题】:pointer to char changes after opendir() system callopendir() 系统调用后指向 char 的指针发生变化
【发布时间】:2015-02-24 20:36:32
【问题描述】:

我目前正在尝试使用 c 从系统调用中删除目录,但我遇到了一个奇怪的问题。在我的deleteFunction()之后使用char * path打开目录。 path 的值发生变化

这里是部分代码:

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

void deleteDir(char *path){
    //opening the directory
    printf("BEFORE %s\n",path );
    DIR *p = opendir(path);
    if (p == NULL){
        printf("Directory not Opened!\n");
        exit(2);
    }
    printf("AFTER %s\n",path );
}

void main(int argc,char *argv[]){

    if (argc != 2){
        printf("Not enough Arguments!\n");
        exit(1);
    }

    //creating the path 
    char * currentDir = getcwd(NULL,0);
    strcat(currentDir,"/");
    strcat(currentDir,argv[1]);
    //deleting the directory
    deleteDir(currentDir);
    exit(0);
}

产生的输出是:

BEFORE /home/tarounen/test/newfolder
AFTER /home/tarounen/test/!�

注意:我只是将目录名作为参数

【问题讨论】:

  • main 返回int,而不是void。 (这不是您的问题的原因。)

标签: c linux system-calls opendir


【解决方案1】:

getcwd 函数可能分配的空间刚好足以容纳当前路径,因此使用strcat 添加更多字符会溢出缓冲区,并导致未定义的行为。试试这个

char path[MAXPATHLEN];
getcwd( path, MAXPATHLEN );
strcat( path, "/" );
strcat( path, argv[1] );

【讨论】:

    【解决方案2】:

    getcwd 仅在传递NULL 时分配足够的内存来保存目录。
    连接到它的结果有未定义的行为。

    如果要使用strcat,需要为自己的缓冲区提供足够的空间:

    char buffer[MAXPATHLEN] = {0};
    if (getcwd(buffer, sizeof(buffer)))
    {
        strcat(buffer, "/");
        strcat(buffer, argv[1]);
        deleteDir(buffer);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多