1

I want to replace a character (for example the second one) from a string. What's wrong with my code? It can compile, but instead of doing what I need it give me a Segmentation fault. Thanks!

#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main (int argc, string argv[])
{
    string key="abcd";
    key[1]='f';
}

And after compiled my code

~/workspace/pset2/crack/ $ clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow bug.c -lcrypt -lcs50 -lm -o bug
~/workspace/pset2/crack/ $ ./bug
Segmentation fault
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

4 Answers4

0
string key="abcd";

string is basically char * ,key is string literal. You try to modify it, therefore the segmentation fault.

ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

I do not see the definition of name string but I think it is something like char *.

Thus in this declaration

 string key="abcd";

there is declared a pointer to a string literal.

String literals are unmodified in C, Any attempt to modify a string literal results in undefined behavior.

From the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `string` is a typedef from a library called `cs50`, and you got it right -- it's only `char*`. Apparently this library is used in Harvard introductory courses to read from the keyboard. It sounds useful, but this typedef really shouldn't exist. – giusti Dec 04 '16 at 16:31
  • @giusti Thanks for the information.:) – Vlad from Moscow Dec 04 '16 at 16:48
0

You can only modify memory that is in the heap or stack, your "abcd" there is what is known as a String Literal and belongs in the program's read-only memory space, it cannot be modified where it is (not if it's running under any decent operational system anyway).

The reason it's placed there to begin with is because string is basically just a char * pointer, and it will point to any memory space and doesn't care if it's in read-only space or not. (not to be confused with C++ std::string).

To make it modifiable you have to tell C it's not a pointer, but an array.

char key[] = "abcd";

Now C will place this string in the stack where you can modify it at will.

Havenard
  • 27,022
  • 5
  • 36
  • 62
0

This is because "abcd" is not really copied into your key variable. Instead, key is a pointer to this constant string.

If you want to be able to modify it, you can do this :

int main (int argc, string argv[])
{
    char key[] = { "some string" };
    key[1]='f';
}
Julien__
  • 1,962
  • 1
  • 15
  • 25