strcpy(), 2 strings, and segmantation fault

This is a discussion on strcpy(), 2 strings, and segmantation fault within the C Programming forums, part of the General Programming Boards category; What is wrong with the following code? char *string = "adfjk"; char *string2 = "adfjk"; strcpy(string, string2); It produces a ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    4

    Smile strcpy(), 2 strings, and segmantation fault

    What is wrong with the following code?

    char *string = "adfjk";
    char *string2 = "adfjk";
    strcpy(string, string2);

    It produces a segmentation fault.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,781
    You are copying to a string literal. Basically, the destination char array needs to be writable and have enough space to accomodate the chars to be copied.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Resu Deretsiger Nightowl's Avatar
    Join Date
    Nov 2008
    Location
    /dev/null
    Posts
    186
    This is the most major disadvantage of using char *string = "STRING";.

    Use something more like

    Code:
    char string[128] = "string";
    . . . if you must.
    Do as I say, not as I do . . .

    Experimentation is the essence of programming. Just remember to make a backup first.

    "I'm a firm believer that <SomeGod> gave us two ears and one mouth for a reason - we are supposed to listen, twice as much as we talk." - LEAF

    Questions posted by these guidelines are more likely to be answered.

    Debian GNU/Linux user, with the awesome window manager, the git version control system, and the cmake buildsystem generator.

  4. #4
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    Quote Originally Posted by Nightowl View Post
    This is the most major disadvantage of using char *string = "STRING";.
    using the more correct version

    Code:
    const char* string = "STRING";

    will force the compiler to issue warnings when you try to change this string
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  5. #5
    Registered User
    Join Date
    Mar 2009
    Posts
    4

    Smile Thank You

    Thank you for your help. Things make more sense to me now, I had been struggling with some of the basics like that since I have been trying to learn C.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21