0

I am getting a Segmentation fault but I do not know why:

    // Assemble folderPositionString
    char *folderPositionString = "folders-";
    strcat (folderPositionString, "files"); 

In theory this should produce a single char string with 'folders-files' as the value. I have used strcat before and it works, but for some reason it is not happy here.

If I comment out the strcat line, everything compiles and works.

Working Code thanks to Eugene

    char folderPositionString [50] = "folders.";
    strcat (folderPositionString, folderPositionRaw);   
    strcat (folderPositionString, ".files");
Steven Carlson
  • 925
  • 1
  • 10
  • 25
  • 7
    Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – this Nov 11 '15 at 16:26
  • 3
    `char *folderPositionString = "folders-";` is a string literal kept in **read only memory.** You are trying to change data in a **read only memory**, So are getting `seg fault`. – Haris Nov 11 '15 at 16:27

1 Answers1

1

folderPositionString is pointing to a read-only memory where the string literal is allocated. When trying to write there additional data you are getting memory access violation.

Update about the update:

In the second case query_string is getting the same address value as account_id, which is presumably pointing to a non-read only memory region.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
  • 1
    Eugene - On the second part, so I guess I am not taking the 'value' or account_id, rather I am pointing to its actual memory location? I'm guessing I should revisit that code because that might have unintended consequences in that code as well. – Steven Carlson Nov 11 '15 at 16:36
  • 1
    For the 1st part - would it be better to set folderPositionString using [] or do I need to alloc memory differently? – Steven Carlson Nov 11 '15 at 16:37
  • 2
    It is value of `account_id`, which is interpreted as address (i hope for you it is valid). If you change `folderPositionString` to [], yes it will behave differently and just initialize the writable array with this string. But don't forget to set it's size to a sufficient number to contain the concatenated string. – Eugene Sh. Nov 11 '15 at 16:39
  • 1
    Thank you Eugene, that fixed it. I have updated my question with the finalized code. Thanks again :) – Steven Carlson Nov 11 '15 at 16:41
  • 1
    Please revert the original question. It is a Q&A site, which means it has to contain valid questions and answers. – Eugene Sh. Nov 11 '15 at 16:43