Home > Net >  Is the code below correct? how to fix this code
Is the code below correct? how to fix this code

Time:09-11

Is the code below correct?

 char *make_file_name(char *base)
 {
 char *file_name = strdup(base);
 strcat(file_name, ".pcap")
 return file_name;
}

how to fix it

CodePudding user response:

Is the code below correct?

No. Explanation:

char *make_file_name(char *base)
{
 char *file_name = strdup(base); // 1
 strcat(file_name, ".pcap")      // 2
 return file_name;
}
  1. file_name now points to a memory area just big enough to hold a string of the same length as the string pointed out by base.
  2. You here try to concatenate file_name and ".pcap" - but there is not enough space so it'll write out of bounds, with undefined behavior as a result.

The fix is to allocate enough memory for both strings:

char *make_file_name(const char *base) // may as well make it const
{
 size_t blen = strlen(base);
 char *file_name = malloc(blen   5   1);    // blen   strlen(".pcap")   1 for `\0`
 memcpy(file_name, base, blen);
 memcpy(file_name   blen, ".pcap", 5   1);
 return file_name;
}

CodePudding user response:

You need to allocate enough memory before using strdup. You can do this:

char *file_name  = malloc(strlen(base)   6);

before the if condition then after the function is done, you need to deallocate the memory using free()

CodePudding user response:

strdup() allocates memory for the size of base 1 and copies base into that allocated memory.

In your code, when you call strcat(), there is not enough space to concatenate file_name with ".pcap". As a result a out-of-bounds write will occur which invokes undefined behavior.

To fix this you must allocate enough memory for both strings:

char *make_file_name(const char *base)
{
     char *file_name  = malloc(strlen(base)   5   1);

     if (file_name != NULL) {
         strcpy(file_name, base);
         strcat(file_name, ".pcap");
     }

     return file_name;
}

Remember to free() the memory once you are done with it:

char *str = make_file_name("file1");
// use str
free(str);

CodePudding user response:

If you're using GNUC, you can do it very simply:

#include <stdio.h>

char* make_file_name(const char* base) {
  char* buffer = NULL;
  asprintf(&buffer, "%s.pcap", base);
  return buffer;
}
  •  Tags:  
  • c
  • Related