Thread: Modifying a string literal

  1. #1
    Registered User
    Join Date
    Feb 2011

    Modifying a string literal

    Hi everyone. I'm trying to learn C99. In this program, which elements are non-conforming? GCC compiles and runs it, but gives me exc_bad_access on the *(p+1).

    #include <stdio.h>
    int main()
    	char *p = "Hello mother";
    	char  a[] = "Hello father";
    	void* b = a;
    	printf("%s\n", p);
    	printf("%s\n", a);
    	return 0;

  2. #2
    Join Date
    Aug 2010
    Ontario Canada
    That's because you're trying to modify a literal string. p is just a pointer to it.

    The second way will work, but you're going to run into buffer overflows if you either try to replace it with a longer string or use strcat() on it...

    It's usually better to allocate string space somewhat generously...
    char p[100] = "Hello Mother";
    Now you've got some wiggle room...

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Oregon, USA
    	void* b = a;
    As far as I can tell, that shouldn't be valid. Unless I'm mistaken, pointer arithmetic is not allowed on void pointers. Maybe it's a GCC extension that allows it. You could get around it like so, since b points to a char *:
    void* b = a;
    ((char *)b)++;
    If you understand what you're doing, you're not learning anything.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    The title of this thread is something that you cannot do, so I'm not surprised you're having trouble.
    Given we can't help you to do the impossible, your solution is to use an actual array, as you have for the variable a.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about string literal
    By pangzhang in forum C Programming
    Replies: 6
    Last Post: 07-31-2010, 07:25 AM
  2. Polymorphism and generic lists
    By Shibby3 in forum C# Programming
    Replies: 9
    Last Post: 07-26-2010, 05:27 AM
  3. Replies: 60
    Last Post: 05-31-2010, 10:57 AM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

Tags for this Thread