extra \377 copied to buffer char array with memcpy

Viewed 139

I want to read a file (plain text) and see if it contains 12 bytes of data, starting with "CLOSE" and end with "SCDH". I am using memcpy to copy over the buffer string in order to compare consecutive memory address. However, the resulting buffer, buffer_two has an extra \377 at the end. The other variable buffer is able to print out CLOSE if the passing file contains it. I am not sure why I got the extra character for buffer_two.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])  {
   FILE *f = fopen(argv[1], "r");
   int size;
   fseek(f, 0, SEEK_END);
   size = ftell(f);
   rewind(f);
   char *temp = malloc(sizeof(char) * size);
   fread(temp, sizeof(char), size, f);

   int i;
   for (i = 0; i < size - 12; ++i) {
      if (temp[i] == 'F') {
         char buffer[4];
         char buffer_two[4];
         memcpy(buffer, &temp[i], 4*sizeof(char));
         memcpy(buffer_two, &temp[i+8], 4*sizeof(char));
         printf("buffer %s\n", buffer);
         printf("buffer_two %s\n", buffer_two);

         if (memcmp(buffer, "CLOSE", 4) == 0 && memcmp(buffer_two, "SCDH", 4) ==0) {
            return 1;
         }

      }
   }

      return 0;
}

Here is the output from GDB after memcpy

(gdb) print buffer_two
$1 = "SCDH\377"
1 Answers

memcpy does not append a '\0' to the buffer so printf can't tell where the chunk of memory that you treat as a string ends. Either add that terminating '\0' to your buffer:

char buffer[5];
...
buffer[4] = '\0';

or pass in the size to print:

printf("buffer %.*s\n", 4, buffer);

You can write 4 * sizeof(char) as just 4:

When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1. (C.5.3.3)

Related