“检测到堆栈粉碎”通过 getline 和printf - 我真的不明白为什么
当谈到 C 时,我不是菜鸟 - 我更像是一个总和。完全是愚蠢无知的菜鸟!我正在尝试编写一个程序来解析简单的文本文件,并且我想让它尽可能通用(为什么我使用 getline)。这是我的代码:
//afile.c
#include <stdio.h>
#include <stdlib.h>
main( )
{FILE *fp1;
char *filename;
char **line;
size_t *sz;
int s;
filename = "n";
if ((fp1 = fopen(filename,"r")) == NULL ){printf("error...");return 1;}
do {
s = getline(&line,sz,fp1);
if (s != -1)
printf(" %s \n",line);//<-- %s seems to be wrong! %*s removes the gcc warning
} while (s != EOF);
fclose(fp1);}
我很确定它有一些指针分配问题,但我真的不知道它在哪里。我发现用 %s 替换 %s 会使编译器警告消失,但会导致在终端中写入无限的 \t(tabs) 。 顺便说一句,我收到的错误消息是: 检测到堆栈粉碎*:./afile终止 分段错误
when it comes to C i am not a noob - i'm more like a total & complete stupid ignorant noob! i am trying to write a program to parse simple text files, and i would like to make it as general as possible(why i use getline). well here is my code:
//afile.c
#include <stdio.h>
#include <stdlib.h>
main( )
{FILE *fp1;
char *filename;
char **line;
size_t *sz;
int s;
filename = "n";
if ((fp1 = fopen(filename,"r")) == NULL ){printf("error...");return 1;}
do {
s = getline(&line,sz,fp1);
if (s != -1)
printf(" %s \n",line);//<-- %s seems to be wrong! %*s removes the gcc warning
} while (s != EOF);
fclose(fp1);}
I am pretty sure its some pointer allocation problem, but i really cant figure out where it is. i've found out that replacing %s with %s makes the compiler warning disappear, but it results in an infinity of \t(tabs) being written in the terminal.
By the way, the error message i get is:
stack smashing detected *: ./afile terminated
Segmentation fault
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getline
需要一个char**
类型的参数,并且您提供了&line
,即char***
>。此外,getline
作用于其第一个参数指向的值的当前值(因此,line
的值),而您没有' t 初始化它。将您的程序更改为:应该没问题。
getline
expects an argument of typechar**
, and you supplied&line
, which ischar***
. Additionally,getline
acts on the current value of the value its first arguments points to (so, the value ofline
), and you didn't initialize it. Change your program to:and it should be fine.
您未能初始化行变量,它包含一个随机值。 Readline 可能会尝试重新分配()它。
更新:线的定义也是错误的,正如其他人指出的那样,只需要一个星号。
You failed to initialize the line variable, and it contains a random value. Readline probably tries to realloc() it.
UPDATE: the definition for line is also wrong, only one asterix needed, as pointed out by others.
您的指针重定向不一致。变量line声明为:
是一个指向字符的指针,或者是一个指向字符串的指针。 getline() 需要一个指向字符串的指针,但您传递 &line - 一个指向字符串指针的指针。
最后,你指定的 printf() 格式是 %s,它是否想要格式化一个字符串,但你给它一个指向字符串的指针。
长话短说:删除星号来创建
Your pointer redirections are inconsistent. The variable line is declared:
Which is a pointer to a pointer to a character, or a pointer to a string. getline() expects a pointer to a string, but you pass &line - a pointer to a pointer to a string.
Finally, your printf() format specified is %s, do it wants to format a string, but you give it a pointer to a string.
Long story short: remove an asterisk to create