61445

pointer to strings

Question:

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'.

Answer1:

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

Answer2:

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

Answer3:

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.

Answer4:

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; }

Answer5:

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.

Answer6:

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).

Recommend

  • How to convert one data type to another
  • How to send None with Signals across threads?
  • What's the benefit of the trailing apostrophe in character literals
  • SQL Server Nvarchar and Java prepared statement
  • Change border corlor of NSTableView
  • proxy request in node.js / express
  • Sort by a column in a union query in SqlAlchemy SQLite
  • How to protect the mp3 file from read or copy on Android?
  • How to write string.Contains(someText) in expression Tree
  • What do I do with this error when I run tests in rails?
  • CRASH: *** -[__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 9]
  • Nested projects in multiproject visual studio templates
  • Compare struct to a constant in C
  • Wrong labels when plotting a time series pandas dataframe with matplotlib
  • Getting error 'Cannot read property 'document' of undefined' while importing exp
  • NUnit 3.0 TestCase const custom object arguments
  • SAXReader not re-ecape characters
  • Android application: how to use the camera and grab the image bytes?
  • Is playing sound in Javascript performance heavy?
  • Is there a way to do normal logging with EureakLog?
  • Time complexity of a program which involves multiple variables
  • Insert into database using onclick function
  • QLineEdit password safety
  • Counter field in MS Access, how to generate?
  • Accessing IRQ description array within a module and displaying action names
  • Possible to stop flickering java tooltip in heavyweight mode?
  • Javascript Callbacks with Object constructor
  • Knitr HTML Loop - Some HTML output, some R output
  • Where to put my custom functions in Wordpress?
  • sending/ receiving email in Java
  • How to set my toolbar fixed while scrolling android
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • AT Commands to Send SMS not working in Windows 8.1
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • embed rChart in Markdown
  • apache spark aggregate function using min value
  • Sorting a 2D array using the second column C++
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app