C token 循环段错误问题

标签 c segmentation-fault valgrind

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

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

感谢 Advanced Pete。

==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");
}

关于C token 循环段错误问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495793/

相关文章:

c - strtok 行为不一致

c - Valgrind 声称存在未释放的内存。这很糟糕吗?

c++ - 打开 MPI : how to run exactly 1 process per host

c++ - 使用 SSE 指令的 openMP 程序中线程 > 4 的段错误

c - 提交解决方案后Codechef网站中出现段错误

c - 将指向结构的指针设置为等于函数返回的另一个指向结构的指针?

c - C 中的段错误 11 在排序列表中插入节点

c - realloc() C语言改变int数组中的值

c - 传递 argv 语句的不同答案

c - 在不同编译器生成的代码之间传递结构