Thread: strcpy not overwriting (segmentation fault)

  1. #1
    Registered User
    Join Date
    Dec 2018
    Posts
    12

    strcpy not overwriting (segmentation fault)

    Hi, I'm trying to understand why I can't overwrite with strcpy on this piece of code:

    Code:
    int main (int argc, char *argv[])
    {
    	char *str2;
    	char *str = malloc(sizeof(char)*10000);
    
    	str2 = " Long text 1";
    
    	strcpy(str2, "Long text 2");
    		sprintf(str,"%s\n",str2);
    		write(1,str,strlen(str));
    	exit(0);
    }
    I know how to work around this without using strcpy, but I need to use strcpy. I've tried allocating memory to str2 via malloc but it's the same issue. Any idea what this code is doing wrong?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,490
    All string constants are in read-only memory, so you get a segfault if you try to write to them.

    str2 = " Long text 1";
    This works because all you're doing is setting a pointer to point to the string.


    strcpy(str2, "Long text 2");
    This doesn't work because you're physically trying to modify the memory holding " Long text 1"

    It might be a bit more obvious if you were const correct
    const char *str2 = "Long text";
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2018
    Posts
    12
    Quote Originally Posted by Salem View Post
    All string constants are in read-only memory, so you get a segfault if you try to write to them.

    str2 = " Long text 1";
    This works because all you're doing is setting a pointer to point to the string.


    strcpy(str2, "Long text 2");
    This doesn't work because you're physically trying to modify the memory holding " Long text 1"

    It might be a bit more obvious if you were const correct
    const char *str2 = "Long text";
    Thanks for the reply Salem, that was helpful.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In GDB no segmentation fault but while running segmentation fault
    By Tamim Ad Dari in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2013, 11:16 AM
  2. Append or strcpy segmentation fault
    By Eramol in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2012, 08:30 AM
  3. Segmentation Fault With pointer to pointer strcpy
    By touchy in forum C++ Programming
    Replies: 3
    Last Post: 03-09-2011, 12:35 AM
  4. strcpy(), 2 strings, and segmantation fault
    By jigidyjensen in forum C Programming
    Replies: 4
    Last Post: 03-20-2009, 01:42 PM
  5. Segmentation Fault on -> and strcpy line
    By 6thmercury in forum C Programming
    Replies: 5
    Last Post: 04-12-2005, 06:10 PM

Tags for this Thread