Thread: strcat causing segmentation fault?

  1. #1
    Registered User
    Join Date
    Jun 2004

    strcat causing segmentation fault?

    I am having a wierd issue. I am doing a simple strcat and getting a segmentation fault. Here is a code snippet.

    	#include <stdio.h>
                    #include <string.h>
    	printf("2 %s  &  %s\n",sname, name);
    	strcat(sname, name);
    This produces:
    2 / & rb123121
    Segmentation fault (core dumped)

    Any ideas why this would happen? I have string.h included.


    Ok, after playing some more, it seems to be occuring with any string functions. I have all the right libraries included don't I?
    Last edited by jbsloan; 04-02-2005 at 09:20 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    String constants are in read only memory.

    char *s = "hello"; // this is read only (or at least is allowed to be, and is in your case).

    You need a real array of char, or some malloc'ed memory to strcat with

    char s[100] = "hello";
    strcat( s, " world" );
    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
    Jun 2004
    That did it. Thanks a lot!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strtok is causing segmentation fault
    By yougene in forum C Programming
    Replies: 11
    Last Post: 03-08-2008, 09:32 AM
  2. A libdc1394 library function is causing a segmentation fault
    By Phanixis in forum Linux Programming
    Replies: 7
    Last Post: 10-16-2007, 12:44 PM
  3. Segmentation fault on strcat
    By paxmanchris in forum C Programming
    Replies: 9
    Last Post: 04-24-2007, 10:04 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 12:33 PM
  5. strcat segmentation fault
    By captain-cat in forum C Programming
    Replies: 3
    Last Post: 07-20-2004, 10:29 AM