Thread: strange error msg

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    27

    strange error msg

    Hello world!!

    I was trying to make a function that replaces some given string with another given string throughout a give string.

    but a strange error showed up. When I tried small pieces of code the error appeared again with on trying to execute the following code:
    Code:
    void f(char * ptr)
    {
    	*(ptr) = 'a';
    }
    
    int main(void)
    {
    	char * strng = "Hello world. The world is just awesome";
    	puts(strng);
    	f(strng);
    }
    error appears when trying to execute *(ptr) = 'a';

    error msg:
    Code:
    Unhandled exception at 0x011c17a1 in replacing string 2.0.exe: 0xC0000005: Access violation writing location 0x011c5d30.
    Thanks in advance.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    That's because you're trying to change a string literal. No decent compiler will let you do that.

    Code:
    char *string = strdup("! Hello World"); // write to an actual string
    
    *string ='X';
    
    printf("%s",string);
    
    free(string); // because strdup uses malloc()

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Or you can define it this way:
    Code:
    char string[ ] = "Hello World!";
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strange error
    By manzoor in forum C++ Programming
    Replies: 2
    Last Post: 02-27-2008, 11:05 PM
  2. strange bus error
    By Tehy in forum C Programming
    Replies: 8
    Last Post: 05-23-2007, 09:59 PM
  3. Strange error I have not gotten before.
    By tameeyore in forum C Programming
    Replies: 3
    Last Post: 09-16-2005, 11:36 AM
  4. C++ VC6 to VC.NET - strange error
    By torbjorn in forum C++ Programming
    Replies: 9
    Last Post: 06-02-2004, 04:18 AM
  5. Strange error.
    By Will in forum C++ Programming
    Replies: 9
    Last Post: 05-01-2002, 12:25 PM