-1

A very simple C program: I want to put 0's at some points in a string to obtain sub-strings. But at the first try I get segmentation fault on execution:

#include<stdio.h>
#include<string.h>
int main() {
        char *a = "eens kijken of we deze string kunnen splitten";
        a[4] = '\0'; // this causes the segfault
        char *b = a[5]; // sort of guessed this can't work...
        printf("%s", a);
}

So the main question: why the segfault at a[4] = '\0'; Second I'd like to split this string with the least amount of code, based on string-index...

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Niels
  • 537
  • 5
  • 22
  • 2
    In C all string literals are arrays of characters, and they're not allowed to be modified (the arrays are effectively read-only). That's why you should always use `const char *` when pointing to such strings. – Some programmer dude Dec 01 '19 at 08:52

2 Answers2

2

You are trying to change a string literal.

char *a = "eens kijken of we deze string kunnen splitten";

String literals are immutable in C. Any attempt to change 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.

Instead declare a character array

char a[] = "eens kijken of we deze string kunnen splitten";

Also in this declaration

char *b = a[5];

there is a typo. Should be

char *b = &a[5];

or

char *b = a + 5;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • So it is just a matter of writing a[] or * a that defines whether it is a constant char*, right? because essentially they are both just pointers (a[] and *a) – Niels Dec 01 '19 at 09:00
  • @Niels For starters arrays are not pointers. Secondly in the first case the pointer points to a string literal that gas the static storage duration. In the second case when an array is used the elements of the string literals are copied in elements of the array. – Vlad from Moscow Dec 01 '19 at 09:02
1

The variable a pointer to a string literal. These constants are stored in a non-writable section of the resulting executable. Trying to write anything into that area will cause a segfault.

A string array (char a[]='literal';) will put the string into the right place and allow writing.

edit: Your syntax, (de)referencing a char * is correct, but the compiler will treat it differently.

Yotamz
  • 173
  • 4