如何解决C中的无效读取问题

时间:2016-12-28 09:42:18

标签: c realloc

我的程序存在无效的读取问题,我在c中创建了一个简单的shell,它支持历史记录及其内置函数。这是我的问题,我有一个变量

substitute

我运行命令 char *cmd = malloc(sizeof(char) * 256); ,现在是^p^l^,我将cmd = ^p^l^传递给搜索功能,搜索历史记录并返回匹配或相同的字符串。 cmd

ft_man_search_replace(&cmd, &pos, hist)

运行此功能后,似乎void ft_man_search_replace(char **cmd, int *pos, t_stack hist) { char **split; t_search_hist search; int i; // splits ^string^string^ into array split = ft_strsplit(*cmd + 1, '^'); i = *pos; // get previous history and assign it to haystack search.haystack = ft_get_prev_hist(hist); search.needle = split[0]; search.with = split[1]; *cmd = ft_search_replace(search, 0, 0, 0); //if returned string is equal to *cmd, there was no match //assign *cmd to empty string. if (ft_strequ(search.haystack, *cmd)) { ft_putendl("\n21sh: substitution failed"); *cmd = ""; *pos = 0; return ; } i = ft_strlen(*cmd); ft_cursor(*cmd, i + 1, &hist); *pos = i; } 不再有cmd的内存分配,当我输入内容时,我无法读取,我的猜测是我到达了字符串的结尾。例如,如果未找到匹配,我分配256,现在如果我尝试修改*cmd = "",我会得到无效的读取。我怎么解决这个问题?我尝试使用以下功能重新分配,因为我不允许使用cmd

realloc

1 个答案:

答案 0 :(得分:3)

好的,我设法解决了这个问题,因为user3121023指出*cmd =将丢弃内存分配,我决定使用strcpymemset代替=

//libraries here
# define SIZE 256   

char *cmd = malloc(sizeof(char) * SIZE);

void    ft_man_search_replace(char **cmd, int *pos, t_stack hist)
{
    char            **split;
    t_search_hist   search;
    int             i;

    // splits ^string^string^ into array
    split = ft_strsplit(*cmd + 1, '^');
    i = *pos;
    // get previous history and assign it to haystack
    search.haystack = ft_get_prev_hist(hist);
    search.needle = split[0];
    search.with = split[1];
    memset(*cmd, 0, SIZE);
    strcpy(*cmd, ft_search_replace(search, 0, 0, 0));
     //if returned string is equal to *cmd, there was no match
     //assign *cmd to empty string.
    if (ft_strequ(search.haystack, *cmd))
    {
        ft_putendl("\n21sh: substitution failed");
        memset(*cmd, 0, SIZE);
        strcpy(*cmd, "");
        *pos = 0;
        return ;
    }
    i = ft_strlen(*cmd);
    ft_cursor(*cmd, i + 1, &hist);
    *pos = i;
}