格式化字符串中的内存泄漏,正确的空终止

时间:2013-02-02 05:37:36

标签: c char printf ar

我认为我有一个终止字符串的问题,因为我在显示它们时遇到了问题。我正在尝试在C中重新创建unix ar命令,我几乎已经-v布局了,但是现在我已经获得了权限,我似乎无法将它们打印出来。

我在perms数组的末尾添加了一个终止字符,这有助于显示权限,但现在日期不想打印。

当我将日期打印在一个单独的字符串中时,日期会打印出来,但当它与其他所有字符串组合在一起时,它就会消失。

void verbose(char *archive){
    mode_t mode;
    size_t readNum;
    time_t mtime;
    struct tm * time_box;
    long long arch_size, file_size;
    long uID, gID;
    char header[60], file_name[16], time[21], perms[8];
    char* tokens;
    FILE *fp = fopen(archive, "r");
    if (!fp)
        fail('f');

    //get file size
    fseek(fp, 0, SEEK_END);
    arch_size = ftell(fp);
    rewind(fp);

    //move over ARMAG
    if(fseek(fp, strlen(ARMAG), SEEK_SET) != 0)
        fail ('z');

    //loop over files
    while(ftell(fp) < arch_size -1){
        //reads header into
        readNum = fread(header, 1, sizeof(header), fp);
        if(readNum != sizeof(header))
            fail('r');

        tokens = strtok(header, " ");
        strcpy(file_name, tokens);
        mtime = (time_t)(atol(tokens = strtok(NULL, " ")));
        uID = atol(tokens = strtok(NULL, " "));
        gID = atol(tokens = strtok(NULL, " "));
        mode = (mode_t)(strtoul(tokens = strtok(NULL, " "), NULL, 8));
        file_size = atoll(&header[48]);
        time_box = localtime(&mtime);
        strncpy(time, &asctime(time_box)[4], 20);


        printf("Time is %s\n", time);

        perms[0] = mode & S_IRUSR? 'r' : '-';
        perms[1] = mode & S_IWUSR? 'w' : '-';
        perms[2] = mode & S_IXUSR? 'x' : '-';
        perms[3] = mode & S_IRGRP? 'r' : '-';
        perms[4] = mode & S_IWGRP? 'w' : '-';
        perms[5] = mode & S_IXGRP? 'x' : '-';
        perms[6] = mode & S_IROTH? 'r' : '-';
        perms[7] = mode & S_IWOTH? 'w' : '-';
        perms[8] = mode & S_IXOTH? 'x' : '-';
        perms[9] = '\0';

        printf("%s"
                "\t%ld"
                "/%ld"
                "\t\t%lld "
                "%s "
                "%s\n", perms, uID, gID, file_size, time, file_name);

        //move over file
        if(fseek(fp, file_size, SEEK_CUR) != 0)
            fail ('z');
    }
    fclose(fp);
}

示例输出:(偶数行也应该有时间)

Time is Jan 27 16:23:59 2013
rw-r--r--   502/20      28 - b.txt
Time is Jan 27 16:24:06 2013
rw-r--r--   502/20      17 - c.txt
Time is Jan 27 16:24:15 2013
rw-r--r--   502/20      28 - d.txt
Time is Jan 27 16:24:06 2013
rw-r--r--   502/20      17 - c.txt

1 个答案:

答案 0 :(得分:3)

您正在分配perms[8],其大小为8。因此,此选项卡的有效索引将为[0-7]。

指定超出perms[8] = mode & S_IXOTH? 'x' : '-';数组边界的perms[9] = '\0';perms

您的time数组必须在内存perms之后。所以perms[8]perms[9]的行为就像您影响time[0] = '-'然后time[1] = '\0'

time现在等于-,printf会正确显示它。

只需将perms[8]声明更正为perms[10],您就会对良好的变量记忆部分产生影响。