0

Isn't an array basically a const pointer to char?

#include <stdio.h>
#include <string.h>

void f(char* s)
{
    strcpy(s,"ciao");
}

void main()
{
    char str[10]="mamma";
    char * const ptr="papa";

    f(str); // <-- works as expected
    printf("%s\n",str);

    f(ptr); // <-- gives Segmentation fault
    printf("%s\n",str);

}

How does strcpy recognize that I provide a pointer and not an array?

I'm aware that strcpy needs enough space in the destination array, but given that this char * strcpy ( char * destination, const char * source ); is the signature of strcpy, how can I infer that it needs an array as first argument? Also, how can strcpy infer it got passed a constant pointer and not an array?

S E
  • 113
  • 1
  • 7
  • Indeed. Ptr gets written much lower in memory (closer to 0x00000000) then str[0]. Apparently in read-only memory (text segment). (str[0]) 0x7ffca0bae6ee: 6d 61 6d 6d 61 00 (*ptr) 0x5586fdab8a52: 70 61 70 61 00 – S E Dec 04 '19 at 01:16
  • 1
    It is not true that `strcpy` requires an array as its first argument. What `strcpy` requires is a pointer to *writable memory* which is *sufficiently large* to hold a copy of the string pointed to by its second argument. – Steve Summit Dec 04 '19 at 12:07
  • 1
    To prove that `strcpy` does not require an array, try `char *mptr = malloc(10); f(mptr);` – Steve Summit Dec 04 '19 at 12:08
  • 1
    Also, `strcpy` does not "infer it got passed a constant pointer". It *tries* copying to the pointer you give it. The segmentation fault happens because the CPU (and/or the MMU) detects that your program is attempting to write to read-only memory. – Steve Summit Dec 04 '19 at 12:10

0 Answers0