0

What happens behind the scene when a string in double quotes is passed as an argument to a function? Where is memory allocated for that string?

If I do memcpy(ptr, "SINGH", strlen("SINGH")+1);, output is SINGH only. From where is the extra byte copied from?

For below program:

void func(char *ptr) {
    memcpy(ptr, "SINGH", strlen("SINGH"));
    cout << ptr << endl; /* Output is SINGHHELLO */
    /* If I do memcpy(ptr, "SINGH", strlen("SINGH")+1); Output is SINGH only. From where does extra byte is copied from? */
}

int main() {
    char str[11] = "HELLOHELLO";
    char str2[10] = "ABC";
    memcpy(str, "HELLO", strlen("HELLO")); /* Where is memory allocated for string 'HELLO' ? */
    cout << str << endl << str2 << endl;
    func(str);
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • C or C++ - make up your mind. –  Aug 11 '18 at 15:20
  • As with any C-style array, it gets converted to a pointer. In this case to a `const char*` pointer to the first character. – Ron Aug 11 '18 at 15:21
  • edited my question /* If I do memcpy(ptr, "SINGH", strlen("SINGH")+1); Output is SINGH only. From where does extra byte is copied from? */ When used with memcpy, where does extra byte is copied from? – Rohit Singh Aug 11 '18 at 15:32
  • `"SINGH"` is an array of 6 chars and the last char is a null – user7860670 Aug 11 '18 at 15:36

1 Answers1

-1

the "something" is called the string literal and it is just the sequence of chars (which actually is an array) in the the read only memory.

When you call any function which takes a parameters of type pointer to char the address to this string literal (which in the fact is the array of chars) is passed to this function.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • 3
    I'm not the downvoter, but [the type](https://wandbox.org/permlink/7a9dIBHsbRHH8dJx) of string literal is `const char[size]`. – Incomputable Aug 11 '18 at 15:47