strcat causing segmentation fault?

This is a discussion on strcat causing segmentation fault? within the C Programming forums, part of the General Programming Boards category; I am having a wierd issue. I am doing a simple strcat and getting a segmentation fault. Here is a ...

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    9

    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.

    Code:
    	#include <stdio.h>
                    #include <string.h>
    
                    sname="/";
    	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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,417
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Jun 2004
    Posts
    9
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21