0

Here is the whole code:

#include <stdio.h>  //printf
#include <stdlib.h> //malloc
#include <string.h> //memcpy

void main(void)
{
    char* charMem = (char*) malloc(5 * sizeof(char));
    memcpy(charMem, "Hello", 5);

    char charArr[] = "Hello";

    printf(" charMem = %p\n", charMem);
    printf("&charMem = %p\n\n", &charMem);

    printf(" charArr= %p\n", charArr);
    printf("&charArr= %p\n\n", &charArr);

    charMem[2] = 'A';
    charArr[2] = 'A';
}

And output is:

 charMem = 00F8ABB0 //diff
&charMem = 00CFFBB0 //diff

 charArr= 00CFFBA0 //same
&charArr= 00CFFBA0 //same

What is happening behind the compiler that leads to these results?

Semih SÜZEN
  • 163
  • 1
  • 2
  • 14
  • 1) How can the address and the value of charArr can be same? 2) Why the error occurres with a valid statement that compiles without any warning? – Semih SÜZEN Apr 02 '19 at 13:28
  • Also a duplicate of https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha – Andrew Henle Apr 02 '19 at 13:35
  • @AndrewHenle My 2. question was a duplicate so i deleted it. – Semih SÜZEN Apr 02 '19 at 13:40
  • Note that after `memcpy()` your `charMem` does not point to a string because `'/0'` is not accounted for ... and that your `charArr` points to the initial char of a /*readonly*/ 6-byte array. – pmg Apr 02 '19 at 13:44

2 Answers2

2

char* charPtr = "Hello";

"Hello" is a readonly array of char. Modifying its contents is undefined behaviour.

Some programmers like to help themselves with

const char *charPtr = "Hello";

so that the compiler checks for attempted changes to the readonly array contents.

charPtr[2] = 'A'; // attempt to change a readonly/const element
pmg
  • 106,608
  • 13
  • 126
  • 198
2

You declare charPtr as a pointer to char and initialize it to point to a string "Hello".

The string "Hello" is kept in a read-only region of memory, so when you try to modify the 3rd location of the string "Hello" it crashes.

Correct it to declare it so

char charPtr[] = "Hello";

Declaring it like that you will be able to mutate the array charPtr[].

Looking in the annex J.2 Undefined behavior wee see that it is undefined when

— The program attempts to modify a string literal (6.4.5).
alinsoar
  • 15,386
  • 4
  • 57
  • 74