gpt4 book ai didi

c - 内存泄漏,在 C 中的两个字符**

转载 作者:行者123 更新时间:2023-12-02 04:49:43 24 4
gpt4 key购买 nike

标题有点乱,但又不好描述。

在我们的 c 方法中:

char* wc(char** cmds, char** stringstoread, char** filename, char* result)
{

char arr[4];
int count = 0;

while(*(cmds) != NULL)
{
if(strcmp(*(cmds), "-l") == 0) // Check each commands
arr[count++] = 'l';
else if(strcmp(*(cmds), "-c") == 0)
arr[count++] = 'c';
else if(strcmp(*(cmds), "-m") == 0)
arr[count++] = 'm';
else if(strcmp(*(cmds), "-w") == 0)
arr[count++] = 'w';

cmds++;
}


if(count == 0)
{
arr[0] = 'l', arr[1] = 'c', arr[2] = 'm',arr[3] = 'w';
}

while((*stringstoread) != NULL)
{
printf("inputs are %s \n", *(stringstoread));
stringstoread++;
}
return result;
}

我们处于 Debug模式 atm,但截至目前,我们无法弄清楚为什么最后一个 while 循环打印出以下内容:

inputs are input 1 


inputs are input 2


inputs are -l
inputs are -w
inputs are -c
inputs are -m

我们不知道 -l、-w -c 和 -m 是如何进入 stringstoread 的,方法是这样调用的:

  char tresult[10000];
char *tcmds[] = { "-l", "-w", "-c", "-m"};
char *tinput[] = {"input 1 \n\n", "input 2 \n\n"} ;
char *tfilename[] = {"fil 1", "fil 2"} ;

char *tmp = wc(tcmds, tinput, tfilename, tresult);

有点乱,但希望有人能提供帮助,我们是 C 的新手,所以认为我们遇到了对该语言的标准误解。

最佳答案

您需要以 null 终止您的数组。像这样:

char *tcmds[] = { "-l", "-w", "-c", "-m", NULL};
char *tinput[] = {"input 1 \n\n", "input 2 \n\n", NULL} ;
char *tfilename[] = {"fil 1", "fil 2", NULL} ;

原因是您要遍历这些数组,直到遇到空值。但是由于程序中定义的数组没有以空值结尾,因此您可以循环结束它们。

当你的循环结束时,你现在有未定义的行为,任何事情都可能发生。实际发生的情况是,编译器将数组布置成彼此相邻,然后您从一个数组的末尾跑到相邻的数组中。

我没有检查您代码中的任何其他内容。肯定还有更多错误,但我认为这是对本题要点的解释。

关于c - 内存泄漏,在 C 中的两个字符**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19094298/

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