在mempcpy for循环中串行构造一个string导致无穷recursion

下面的代码片断是我目前正在处理的代码的简化。 它的目的是构造一个输出string,通过串联string构造。

#define _GNU_SOURCE #include <argp.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <float.h> #include <math.h> #include <string.h> int main(void) { char *english[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}; char *l_english = malloc(5*sizeof(char)*10+10+1); char *ptr_eng = l_english; for(int i = 0; i<10; i++){ ptr_eng = mempcpy(ptr_eng,english[i],strlen(english[i])); printf("Iteration %d\n",i); } free(l_english); return 0; } 

我在Gentoo Linux下编译gcc 4.8.3。 当我运行上面的程序时,它不会停止,但会占用100%的CPU内核。 用gdb看,结果是mempcpy进入无尽的recursion

现在我已经尝试过的东西:

  1. 展开for循环。 这工作得很好,如果我只是写出指令,而不是使用for循环。
  2. 为mempcpy设置一个不变的大小来复制。 再一次,没有无穷的recursion。
  3. 使用memcpy而不改变循环内的指针'ptr_eng':再次,没有无穷的recursion。
  4. 关于3.使用memcpy并设置eng_ptr = eng_ptr+strlen(english[i]) 。 再一次发生无尽的recursion。

不幸的是,当我Google for memcpy和for-loop时,我只能find关于性能的讨论。 我是C的新手,我会很感激你能提供的任何指针。

编辑

这是一个链接到相关的gdb输出http://pastebin.com/nBZhqnsw ; 这继续直到发生段错误。

编辑2

清除事情:上面的代码只是我目前正在编写的一个程序的一个简单的例子。 malloc调用中的大小公式实际上只是一些用于计算实际程序中所需的实际内存量的variables的一次性replace。 这个例子唯一重要的是它有足够的内存来保存englishvariables中的十个单词。

预期的结果是,l_english是一个指向“zeroonetwothreefourfivesixseveneightnine”的内存块开始的指针。 就像我说的,这只是为了堆栈溢出而进行的简化。

我不知道为什么它不起作用,所以我只是建议你保持程序简单,一切都会运行良好:

 #include <stdlib.h> #include <string.h> #include <stdio.h> int main(void) { const char* english[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; char *l_english = malloc(5*sizeof(char)*10+1); // 5 chars times 10 plus nul char *ptr_eng = l_english; for(size_t i=0; i<10; i++) { const char* ptr_ch = english[i]; while(*ptr_ch != '\0') { *ptr_eng = *ptr_ch; ptr_eng++; ptr_ch++; } printf("Iteration %d\n",i); } *ptr_eng = '\0'; puts(l_english); free(l_english); return 0; } 

输出:

 Iteration 0 Iteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5 Iteration 6 Iteration 7 Iteration 8 Iteration 9 zeroonetwothreefourfivesixseveneightnine 

另外,上面的while循环比memcpy + strlen更有效率。

这是问题:我编译我的代码与GCC在Linux下–std = c99。 在@Joachim Pileborg提供的关于我的问题的评论中,我看到了选项–std = gnu99。

出于纯粹的绝望,我试了一下……程序运行顺利。 编译器在那里显然做了一些有趣的事

感谢大家的意见。