Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 字符串内存问题:使用printf打印字符串似乎会覆盖自身_C_String_Malloc_Trie - Fatal编程技术网

C 字符串内存问题:使用printf打印字符串似乎会覆盖自身

C 字符串内存问题:使用printf打印字符串似乎会覆盖自身,c,string,malloc,trie,C,String,Malloc,Trie,我开始使用麻省理工开放式课程介绍课程学习C(课程可以找到)。我正在学习其中一个作业,其中您必须编写函数,以使用给定模板(在名为prob2.c的文件中找到)将trie结构实现为英法词典。基本上,程序应该要求翻译一个单词,在trie中查找,然后给出翻译。我第一次尝试自己实现它,但我一直遇到一个错误,结果似乎是打印“覆盖”了自己。这是一个正在发生的事情的例子,因为解释起来有点奇怪: Enter word to translate: Adam ,Adamo> Adam Enter word to

我开始使用麻省理工开放式课程介绍课程学习C(课程可以找到)。我正在学习其中一个作业,其中您必须编写函数,以使用给定模板(在名为prob2.c的文件中找到)将trie结构实现为英法词典。基本上,程序应该要求翻译一个单词,在trie中查找,然后给出翻译。我第一次尝试自己实现它,但我一直遇到一个错误,结果似乎是打印“覆盖”了自己。这是一个正在发生的事情的例子,因为解释起来有点奇怪:

Enter word to translate: Adam
,Adamo> Adam
Enter word to translate: word
,parole mot
Enter word to translate: hello
,eh oh-> salut
Enter word to translate: tree
tree -> arbre
对于这些输入,应如下所示,以便翻译仅由逗号分隔:

Enter word to translate: Adam
Adam -> Adam,Adamo
Enter word to translate: word
word -> mot,parole
Enter word to translate: hello
hello -> salut,allo,eh oh
Enter word to translate: tree
tree -> arbre
在放弃并查看解决方案后(找到了,请参见问题6.2,完整的问题描述也包括在内),我的代码与给出的代码没有太大区别。不管怎样,我使用OCW上发布的解决方案再次编译,似乎没有任何变化。我试着用valgrind运行程序,看看是否有任何明显的内存问题可以解释这一点,但在查找单词时没有出现任何问题,只是在最后释放trie时出现了一些问题

以下是我怀疑可能是主要问题的功能(这是我在文章前面链接的解决方案):

/*将单词添加到trie,并进行翻译
输入:单词和翻译
输出:如果添加了新节点,则为非零,否则为零
后置条件:单词存在于trie中*/
int add_单词(常量字符*单词,字符*翻译){
结构s_trie_node*pnode=proot;
int i,len=strlen(word),inew=0;
无符号字符j;
对于(i=0;ichildren[j]))
pnode->children[j]=新建_节点();
pnode=pnode->children[j];
}
if(pnode->translation){
/*连接字符串*/
char*oldtransation=pnode->translation;
int oldlen=strlen(旧翻译),newlen=strlen(翻译);
pnode->translation=malloc(oldlen+newlen+2);
strcpy(pnode->translation,oldtranslation);
strcpy(pnode->translation+oldlen,“,”);
strcpy(pnode->translation+oldlen+1,translation);
免费(旧译);
}否则
pnode->translation=strcpy(malloc(strlen(translation)+1),translation);
返回inew;
}

如果有人能向我解释为什么会发生这种情况以及如何解决它,我将不胜感激

输入的翻译带有CRLF结尾,但解析代码正在查找LF终止符。因此,每个译文的结尾都有一个CR,就在
add\u word
添加的逗号之前。因此,当您打印它们时,CR会使它们在屏幕左边缘一个接一个地打印

Add_word
中添加测试以确认这一点

if (pnode->translation[oldlen-1] == '\r') ...

啊,行尾疯狂的乐趣。测试出来,你是对的。现在只对load_dictionary()函数做了一点小小的调整,如果回车符跟随换行符,就可以剪切回车符。这么简单的解决方案,我完全认为答案会复杂得令人烦恼。非常感谢你!
if (pnode->translation[oldlen-1] == '\r') ...