C 令牌循环段错误问题

C token loop segfault issue

对 C 来说有点新,我正在尝试创建一个侦听器,以便用户必须按两次 enter 才能完成输入。然后通过新行和 运行 通过循环拆分所有数据并通过我的函数发送它们。

我不确定我做错了什么但是当代码中“//segfaulting at loop”下的循环被注释掉时运行很好但是当我取消注释并有我对“// assemble(ftemp);”的调用评论说它是段错误所以我在这里知道它只是不知道是什么。如果有帮助,Valgrind 会在下面说。

感谢高级皮特。

==14639== Invalid read of size 1

==14639==    at 0x4E7754C: ____strtod_l_internal (strtod_l.c:608)

==14639==    by 0x4011F8: main (in /home)

==14639==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

==14639== Process terminating with default action of signal 11 (SIGSEGV)

==14639==  Access not within mapped region at address 0x0

==14639==    at 0x4E7754C: ____strtod_l_internal (strtod_l.c:608)

==14639==    by 0x4011F8: main (in /home)

==14639==  If you believe this happened as a result of a stack

==14639==  overflow in your program's main thread (unlikely but

==14639==  possible), you can try to increase the size of the

==14639==  main thread stack using the --main-stacksize= flag.

==14639==  The main thread stack size used in this run was 8388608.

==14639== HEAP SUMMARY:

==14639==     in use at exit: 0 bytes in 0 blocks

==14639==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated

==14639== All heap blocks were freed -- no leaks are possible

==14639== For counts of detected and suppressed errors, rerun with: -v

==14639== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

我的代码:

int main(int argc, char * argv[]) {

printf("Please Enter In Float (Hit Enter Twice To Exicute)\n" );
#define MAXLENGTH 1000
char Input_string[MAXLENGTH];
int ilop = 0;
for(;;++ilop)
{
    Input_string[ilop] = getchar();
    if (ilop > 0 && Input_string[ilop] == '\n' &&
 Input_string[ilop-1] == '\n') break;
}
Input_string[ilop] = 0;

 char *pch;
//  printf ("Splitting string \"%s\" into tokens:\n",Input_string);
pch = strtok (Input_string,"\n");
float ftemp = atof(pch);
//printf("price:, %f\n\n",ftemp);

assemble(ftemp);
 //segfaulting at loop
while (pch != NULL)
{
 pch = strtok (NULL, "\n");
 ftemp = atof(pch);
   printf("price:, %f\n\n",ftemp);
//   assemble(ftemp);
 }


 return 0;
 }

为了扩展 Igal S. 所说的内容,您首先要在循环内设置 strtok,然后使用它,直到循环顶部才检查它。因此,在最后一次迭代中,它将 pch 设置为 NULL,然后将其传递给 atof() 而无需检查。

你需要类似(未测试)的东西:

pch = strtok (Input_string, "\n");
while (pch != NULL)
{
  /* ... */
  pch = strtok (NULL, "\n");
}

存在数组越界访问的可能性,这可能会导致未定义的行为。

在开始的for循环中添加检查

if(ilop > 999)
{
   break;
}