-1

Hi i am writing a simple c program to test parsing a buffer in c but when i run the program i get the following errors:

./test.c: line 4: syntax error near unexpected token `('
./test.c: line 4: `int main()'

Does anyone know why these errors are occurring? Thanks

#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);
}
JeremyP
  • 84,577
  • 15
  • 123
  • 161
Jamie Dale
  • 69
  • 1
  • 7

3 Answers3

6

I think you are trying to run source code without compiling. That's not the proper way to do.
First compile the source code

gcc test.c -o test

Then execute it

./test
niyasc
  • 4,440
  • 1
  • 23
  • 50
1

After

buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";

do not

free(buf);

I suppose you should do

strncpy(buf, "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n", 100);

instead of

buf = "GET /index.html HTTP/1.1\n Host: www.gla.ac.uk\n";

And correct mallocing looks like:

char* buf = (char *)malloc(100 *sizeof(char));
VolAnd
  • 6,367
  • 3
  • 25
  • 43
0

You actually want a copy of your string, as the string literal you'd like to assign is constant. You can use strdup, or probably safer, use strndup to make a copy of the string. This does implicitly use malloc, so you should free it afterwards.

Jan
  • 293
  • 1
  • 11