解析输入 c 时出错
error when Parsing input c
您好,我正在编写一个简单的 C 程序来测试在 C 中解析缓冲区,但是当我 运行 该程序时,出现以下错误:
./test.c: line 4: syntax error near unexpected token `('
./test.c: line 4: `int main()'
有谁知道为什么会出现这些错误?
谢谢
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* command;
char* buf = malloc(100 *sizeof(char));
buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";
command = strtok(buf, " ");
printf("%s", command );
free(buf);
}
之后
buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";
没有
free(buf);
我想你应该这样做
strncpy(buf, "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n", 100);
而不是
buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";
正确的 mallocing 看起来像:
char* buf = (char *)malloc(100 *sizeof(char));
我认为您正在尝试 运行 不编译的源代码。那不是正确的做法。
先编译源码
gcc test.c -o test
然后执行
./test
您实际上想要 copy 字符串,因为您要分配的字符串文字是常量。您可以使用 strdup
,或者可能更安全,使用 strndup
来复制字符串。这确实隐含地使用了 malloc,因此您之后应该 free
它。
您好,我正在编写一个简单的 C 程序来测试在 C 中解析缓冲区,但是当我 运行 该程序时,出现以下错误:
./test.c: line 4: syntax error near unexpected token `('
./test.c: line 4: `int main()'
有谁知道为什么会出现这些错误? 谢谢
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* command;
char* buf = malloc(100 *sizeof(char));
buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";
command = strtok(buf, " ");
printf("%s", command );
free(buf);
}
buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";
没有
free(buf);
我想你应该这样做
strncpy(buf, "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n", 100);
而不是
buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";
正确的 mallocing 看起来像:
char* buf = (char *)malloc(100 *sizeof(char));
我认为您正在尝试 运行 不编译的源代码。那不是正确的做法。
先编译源码
gcc test.c -o test
然后执行
./test
您实际上想要 copy 字符串,因为您要分配的字符串文字是常量。您可以使用 strdup
,或者可能更安全,使用 strndup
来复制字符串。这确实隐含地使用了 malloc,因此您之后应该 free
它。