2

If I need to copy a string, src into the array, dest, using strcpy or strncpy, should I allocate an arbitrarily large sized array (like char dest[1024] for example) or should I calculate the size of src using something like strlen and then dynamically allocate a block using malloc (strlen(src) * sizeof(char)).

The first approach seems "easier" but wouldn't I be consuming more space than I needed? And in some cases it might even fall short. On the other hand, the second approach seems more precise but tedious to do every time and I would have to deallocate the memory everytime.

Is this a matter of personal taste or is one of the above preferable over the other?

First User
  • 704
  • 5
  • 12
  • 1
    If you use `strcpy`, unless you are **sure** your string is long at max 1023 + NUL (for a `char dest[1024]`), you **must** use `malloc` (or `calloc` but useless) or `strncpy` (but remember that you have to add manually the NUL) – xanatos Jan 02 '21 at 17:19

3 Answers3

2

The simplest way is to use the strdup() function, which effectively merges the strlen(), malloc() and strcpy() calls into one. You will still need to call free() to release the allocated data in the same way.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
1

The second approach is more secure than the first one. It will fail if you are dealing with a large string. You should also take into consideration the END OF STRING character '\0' when allocating memory for your new string. I

Ismail El Moudni
  • 622
  • 2
  • 9
  • 19
1

It depends on several factors.

If you know the maximum size of the source string in advance and it's not too big (i.e. less than 1K or so) and the destination doesn't need to be used after the current function returns, then you can use a fixed size buffer.

If the source string could be arbitrarily large, or if you need to return the destination string from the function, then you should allocate memory dynamically. Note that if you use malloc (strlen(src) * sizeof(char)) that 1) sizeof(char) is always 1 so you can omit it, and 2) you didn't allocate space for the terminating null byte. So you would need malloc (strlen(src) + 1). Also, you can do the allocation and copying in a single operation using strdup if your system has that function.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • This was very helpful. Thanks. One thing though: if I am to return the block from a function shouldn't the responsbility of deallocating the block be on the function *to which* it was returned? – First User Jan 02 '21 at 17:54
  • 1
    @FirstUser Yes, if your function returns a pointer to memory that it allocated, it is up to the caller to deallocate it. – dbush Jan 02 '21 at 17:57