1

I receive TFTP packets (read requests) using recvfrom with a 512 byte buffer.

The string (file name to be transfered) starts at the third byte of the buffer. The first two are reserverd for the opcode.

I wrote the following function:

char * parseFileName(char * buffer){
    char * filename;

    for(int i = 0; buffer[i] != '\0'; i++)
        *(filename + i) = buffer[i];

    *(filename + i) = '\0';

    return filename;
}

and I call it considering the opcode offset:

char * filename = parseFileName(buffer + 2);

However, this doesn't work and the program stops:

printf("%s", filename);

Unless I add this:

printf("\n");

right before the return statement in the parseFileName function. Only then I can print the filename string on the calling function.

Why is that happening ?

auth private
  • 1,318
  • 1
  • 9
  • 22
paranoidhominid
  • 1,379
  • 2
  • 8
  • 14

1 Answers1

2

Because you are not allocating any memory for char* filename.

If you know that string starts at buffer+2 and has \0 terminator then you can directly do:

char* parseFileName(char* buffer) {
  return strdup(buffer);
}

char* fileName = parseFilename(buffer+2);

Mind that this requires a free when you are done with the file name.

Jack
  • 131,802
  • 30
  • 241
  • 343