3

I was looking through the manuals on strcpy() and strcat(). Seems there's no way to evaluate the "success" of the function call. (ie return value will never be NULL), is that correct?

It's just assumed that if you follow the rules for the input of these functions that the output will be valid? Just wanted to make sure I wasn’t missing anything here…

Mike
  • 47,263
  • 29
  • 113
  • 177

3 Answers3

5

These functions cannot fail in any well-defined way. They will either succeed, or things have gone horribly wrong (e.g. missing 0 char or too small output buffer), and anything could happen.

amaurea
  • 4,950
  • 26
  • 35
1

Because I don't think functions like that really have any way of knowing what "success" is. For instance, strcpy is really just memcpy. So as far as C is concerned, it is just taking data from one memory location and copying it to another. It doesn't know how the data is supposed to look, or be formatted in ways you expect. I guess the only real way you'd know if there is a success or not is if you end up getting a segfault or not.

Kiith Nabaal
  • 366
  • 2
  • 5
  • 16
1

These functions are guaranteed to work, provided that you're not invoking undefined behaviour. In particular, the memory that you're writing to needs to be allocated. There is really no way for them to fail except crashing your program.

Generally, because it can be hard to tell how many bytes will be written, use of these functions is discouraged. Use strncpy and strncat if you can.

Thomas
  • 174,939
  • 50
  • 355
  • 478