C: What size should you allocate to a string array to be passed to strcpy, to be copied into.?

Viewed 122

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?

3 Answers

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.

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

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.

Related