首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++中动态字符的奇怪行为**

问C++中动态字符的奇怪行为**
EN

Stack Overflow用户
提问于 2017-07-09 13:19:14
回答 1查看 44关注 0票数 1

很久以前我曾经用C语言编写代码,现在我似乎失去了我的能力。

我在使用动态char *数组时遇到了一些奇怪的行为。我有一个curses窗口(在另一个文件中实现),用于显示本地计算机上活动的CU和TTY设备的字符串列表。我尝试用calloc对一个char **数组进行零初始化,然后每次(dir->d_name)匹配我的字符串比较时将它增加一个合适的大小。

问题是,这些字符串在运行程序时一半时间显示,另一半时间显示乱码或空白。

我怀疑这是一个与malloc()或calloc()相关的内存/指针问题,但几天来我一直无法确定我的误解。代码如下:

代码语言:javascript
复制
#include <stdio.h>
#include "funcs.h"
#include <ncurses.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>

#define arraysize(ar) sizeof(ar)/sizeof(ar[0])

int main(void) 
{
    char ch;
    const char tty[4] = "tty.";
    const char cu[3] = "cu.";
    const char *directory = "/dev/";
    const char **devices = calloc(0,sizeof(const char *));

    // Initial device list gen //

    DIR *d;
    struct dirent *dir; 
    int count=0;
    d = opendir(directory); 
    if (d != NULL)
    {
        while((dir = readdir(d)))
        {
            if(strncmp(dir->d_name,tty,4)==0 || strncmp(dir->d_name,cu,3)==0)
            {
                count++;
                devices = realloc(devices,(count+1)*sizeof(const char *));
                devices[count-1] = (dir->d_name);
            }   
        }
        closedir(d);    
    }
printf("\n%d\n",count);

struct display MAIN = screen_init();

// Display List //

list_devices(devices,count,MAIN.devpad);
while(ch != 'q')
{
    ch = getch();
}
endwin();
}

感谢您的时间/关注。

EN

回答 1

Stack Overflow用户

发布于 2017-07-09 13:34:53

这里最大的问题是您没有复制dir d_name缓冲区。就像手册上说的:

对于同一目录流,后续对readdir()的调用可能会覆盖readdir()返回的数据。

这意味着您需要显式地复制它:

代码语言:javascript
复制
devices[count-1] = strdup(dir->d_name);

这应该会消除很多乱码。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44993238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档