intex0075
intex0075

Reputation: 115

pointer to strings

The following two code snippets compiles without any errors/warnings but while running it crashes. Kindly enlighten me.

Program 1

 int main( )
{
   char *p= "Hello" ;

   *p = 'B' ;
    printf("\n%s",p);

   return 0;
}

Program 2

int main( )
{
   char *p= "Hello" ;
   Char *q="mug"
   *q = *p ;
    printf("\n%s",q);

   return 0;
}

For program 2 i expected output to be 'Hug'.

Upvotes: 0

Views: 4231

Answers (6)

JoeFish
JoeFish

Reputation: 3100

When you do:

char *p= "Hello";

You are defining a string literal. String literals are constant data and as you've found out, modifying them results in undefined behavior (often a crash). It should be declared as:

const char *p = "Hello";

So the compiler will throw an error if you try to modify it.

Now if you define it instead as:

char p[] = "Hello";

The memory is then allocated on the stack and you can modify it.

int main(int argc, char *argv[])
{
    char p[] = "Hello" ;

    *p = 'B' ;
    printf("\n%s",p);

    return 0;
}

Outputs Bello

For program 2, note only q needs to be on the stack. p can remain a const pointer to a string literal, since you're only reading from it.

int main( )
{
    const char *p = "Hello" ;
    char q[] = "mug";
    *q = *p ;
    printf("\n%s",q);

    return 0;
}

Outputs Hug

Upvotes: 8

user811773
user811773

Reputation:

The strings "Hello" and "mug" are stored in read-only memory and you are trying to write there.

$ gcc -S a.c
$ cat a.s
    .file   "a.c"
    .section        .rodata
.LC0:
    .string "Hello"
.LC1:

Note that the section is "rodata" (read-only data).

Upvotes: 0

user1118321
user1118321

Reputation: 26335

What you should write is:

char p[] = "Hello";

The form above (char p [] = "Hello") tells the compiler, "I've got an array of values coming up, please allocate as much space as is needed for them." It also works with ints, for example:

int i [] = { 1, 2, 5, 100, 50000 };

You'll end up with i being a pointer to an array of 5 values.

Upvotes: 0

Kamyar Souri
Kamyar Souri

Reputation: 1923

I changed program 2 to not use string literals. It shows "Hug" as you expected.

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

int main( )
{
   char p[10];
   char q[10];
   strcpy(p,"Hello");
   strcpy(q,"mug");
   *q = *p ;
   printf("\n%s",q);

   return 0;
}

Upvotes: 0

Prashanth Raghu
Prashanth Raghu

Reputation: 473

When you create a static string in the form of char *p = "test" the contents of the pointer cannot be changed. In your case trying to modify the contents of the pointer yields to the error that you are observing.

Upvotes: 0

H&#229;vard S
H&#229;vard S

Reputation: 23876

In both samples you are modifying string literals, which yields undefined behavior.

Upvotes: 0

Related Questions