1

Folks, I have basic and simple question on pointers. The below is code is giving a segmentation fault.

int main()

{

    char *str = "hello, world\n";

    char *strc = "good morning\n";

    strcpy(strc, str);

    printf("%s\n", strc);

    return 0;

}

Can't we copy from pointer to other.

  1. if i have char *strc = "good morning\n", can't i do like this strc[5] = '.';. Why this also giving a seg fault.
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Reshmi khanna
  • 89
  • 2
  • 5
  • 1
    Similar questions have been asked here 10,000 times. No you can't, variable `strc` is pointing to a RO memory segment within the executable image. Change `char *strc` to `char strc[]` and it will be pointing to (allocated on) the stack. – barak manos Nov 19 '14 at 19:57
  • Yes, i know that. i want to know, what is the reason. – Reshmi khanna Nov 19 '14 at 19:58
  • 2
    Please note that with `char strc[] = "good morning\n"`, the literal string itself will still be allocated in a RO memory segment, but every time the function is called, that string will be copied into the stack (i.e., into the `strc[]` array). – barak manos Nov 19 '14 at 20:04

1 Answers1

2

You may not change string literals. It is what you are trying to do in statement

strcpy(strc, str);

that is you are trying to overwrite string literal "good morning\n" pointed to by pointer strc.

Of cource you may use pointers in function strcpy. The valid code can look like

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

int main()
{
    char *str = "hello, world\n";

    char strc[] = "good morning\n";

    strcpy(strc, str);

    printf("%s\n", strc);

    return 0;
}

Or

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

int main()
{
    char *str = "hello, world\n";

    char *strc = malloc( 14 * sizeof( char ) );
    strcpy( strc, "good morning\n" );

    //...

    strcpy(strc, str);

    printf("%s\n", strc);

    free( strc );

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335