-1

I'm new to c and I was trying to do simple stuff to learn about strings and char arrays, I'm stuck in this section of code.

 const char *words(int count) {
  char *words = "words";
  if(count==1) {
    words[strlen(words)-1] = '\0';// segmentation fault
  }
  return words;
}    

what it does is returning word when count equals one and returns words otherwise. my question is why is this line of code problematic, why I cant look at string as an array of char's

words[strlen(words)-1] = '\0';

I tried to declare the string(array of chars ) in a different way like
char *words = {'w','o','r','d','s'}; but I still get a segmentation fault.

Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
  • Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – Mark Benningfield Mar 17 '18 at 17:40

1 Answers1

2

ISO/IEC 9899:TC3 N1256
6.7.8 Initialization - 32, EXAMPLE 8 The declaration

char s[] = "abc", t[3] = "abc";

defines ‘‘plain’’ char array objects s and t whose elements are initialized with character string literals. This declaration is identical to

char s[] = { 'a', 'b', 'c', '\0' },
t[] = { 'a', 'b', 'c' };

The contents of the arrays are modifiable. On the other hand, the declaration

char *p = "abc";

defines p with type ‘‘pointer to char’’ and initializes it to point to an object with type ‘‘array of char’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.


In short, you try to modify the content pointed by words which is declared as char * words = "words", and the string literal "words" is usually stored in read-only section, that's why you got a SEGSEV.

poming
  • 378
  • 1
  • 2
  • 12
  • "If an attempt is made to use p to modify the contents of the array, the behavior is undefined." i see ...that was the problem but your suggestion is not helping, i want to return the array words, but i cant return words as local variable, the solution is to declare it in the heap bu i dont know any other way than using apointer, can i use malloc/calloc here? is it necessary? – Baraa Natour Mar 17 '18 at 12:45
  • Oh I don't notice you want to return an array. Yes malloc is necessary – poming Mar 17 '18 at 13:12