paxmemento
paxmemento

Reputation: 291

Handling function return value of pointers passed as argument in C

My question involves methods like memset and strcat that return pointers that were passed as arguments. For instance:

Case 1:

const char *src = /*assign space*/;
char *dst = /*assign space*/;
dst = strcat(dst, src);

Case 2:

const char *src = /*assign space*/;
char *dst = /*assign space*/;
strcat(dst, src);

Can case 2 be considered unsafe peradventure the called function changes the memory pointed to. Should the explicit reassignment of case 1 be used always?

If to use case 2, can a variant:

char * const dst = /*assign space*/;

be used to ensure that the pointer remains the same after the call?

Upvotes: 0

Views: 61

Answers (3)

tux3
tux3

Reputation: 7320

Both of your cases would be just as safe, but the extra assignment in the first one is not needed.

strcat doesn't reallocate anything, and doesn't "changes the memory pointed to", so there's no need to take the return value here. The pointer is guaranteed to remain the same after the call.

Upvotes: 3

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

"Normally" you don't use explicit assignment, this is enough

strcat(dst, src);

the returned pointer and the passed pointer both contain the same address, i.e. the address of the memory you previously allocated.

  • It's safe to do any of the two, assigning a pointer to itself doesn't make much sense though.

This was extracted from the linux manual for strcat()

  A simple implementation of strncat() might be:

       char*
       strncat(char *dest, const char *src, size_t n)
       {
           size_t dest_len = strlen(dest);
           size_t i;

          for (i = 0 ; i < n && src[i] != '\0' ; i++)
               dest[dest_len + i] = src[i];
           dest[dest_len + i] = '\0';

          return dest;
       }

as you can see, dest is not changed so the returned pointer and the passed pointer point to the same address.

And this

char * const dst = /*assign space*/;

will not let you do

dst = strcat(dst, src);

so, it forces you to use the first method anyway.

Upvotes: 0

Eric Pruneau
Eric Pruneau

Reputation: 91

dst will not change. dst must be large enough to contain the concatenated string.

So no memory is allocated by strcat().

Upvotes: 2

Related Questions