开发者

Possibility of strcat failing?

开发者 https://www.devze.com 2022-12-16 07:31 出处:网络
Is there a possibility that strcat can ever fail? If we pass some incorrect buffer or string, then it might lead to memory corruption. But, apart from that is it possible that this function can retur

Is there a possibility that strcat can ever fail?

If we pass some incorrect buffer or string, then it might lead to memory corruption. But, apart from that is it possible that this function can return failure like strcat returni开发者_C百科ng NULL even if destination string passed is Non-NULL? If no, why strcat has a return type specified at all?

I have just mentioned strcat as an example. But, this question applies to many string and memory related (like memcpy etc) functions. I just want to know the reasoning behind some of these seemingly "always successful" functions having return types.


Returning a pointer to the target string makes it easy to use the output in this sort of (perhaps not-so-clever) way:

int len = strlen(strcat(firstString, secondString));


Most of them go back to a time when C didn't include 'void', so there was no way to specify that it had no return value. As a result, they specified them to return something, even if it was pretty useless.


The implicit contract of these functions is the following: if you pass-in pointers to valid strings, then the functions will perform as advertised. Pass-in a NULL pointer, and the function may do anything (usually, it will raise a SIGSEGV). Given that the arguments are valid (i.e., point to strings) then the algorithms used can not fail.


I always ignored the return types (wondering who uses them) until today I saw this in glibc-2.11 (copied exactly from the source file) and everything became much more clear:

wchar_t *
wcsdup (s)
     const wchar_t *s;
{
  size_t len = (__wcslen (s) + 1) * sizeof (wchar_t);
  void *new = malloc (len);

  if (new == NULL)
    return NULL;

  return (wchar_t *) memcpy (new, (void *) s, len);
}

It makes it easier to write less code ("chain" it?) I guess.


Here's a pretty standard implementation of strcat from OpenBSD:

char *
strcat(char *s, const char *append)
{
        char *save = s;

        for (; *s; ++s);
        while ((*s++ = *append++) != '\0');
        return(save);
}

As long as the inputs passed to it are valid (i.e. append is properly terminated and s is large enough to concatenate it), this can't really fail - it's a simple memory manipulation. That memory is entirely under the control of the caller.

The return value here could be used to chain concatenations, for example:

strcat(strcat(s, t1), t2);

Although this is hardly efficient...

0

精彩评论

暂无评论...
验证码 换一张
取 消