0

I have the following code. I initialized 2 pointers, one at the beginning and another at the ending of a string. After every step, I increment the 1st pointer and decrement the second pointer. I copy the value of first pointer into the second if the value obtained by dereferencing 1st pointer is less than the value obtained by dereferencing 2nd pointer.

#include <stdio.h>
#include <string.h>

int main() {
   char *word="aacdbc";
   char *p=word;
   char *q=word+(strlen(word)-1);
   printf("\n%s\n",word);
   int i;
   for(i=1;i<=strlen(word)-1;++i) {
      if(*p<*q) {
         *q=*p;
      }
      ++p;
      --q;
   }
   printf("\n%s\n",word);
   return 0;
}

But the code shows a "Segmentation fault error". In which line did I make a mistake?

0

2 Answers 2

4

String literals in C (and C++) are immutable. So your attempt to change the string literal pointed to by the variable word

char *word = "aacdbc";

has undefined behaviour.

Change the definition from a pointer to an array

char word[] = "aacdbc";

The program could look the following way

#include <stdio.h>

int main( void )
{
   char word[] = "aacdbc";
   char *p = word;
   char *q = word+ + sizeof( worrd ) - 1;

   printf( "\n%s\n", word );

   while ( p < q && p < --q )
   {
      if ( *p < *q ) *q = *p;
      ++p;
   }

   printf( "\n%s\n", word );

   return 0;
}
Sign up to request clarification or add additional context in comments.

6 Comments

It might be worth also mentioning how the string literal is stored in the code segment (RO), while the array is in the stack (RW). stackoverflow.com/questions/16021454/…
@Dogbert: That's an implementation-detail that might be so, or might not.
@Deduplicator That type of detail is common across all ANSI-compliant C compilers, and is not limited to a specific platform or OS.
@Dogbert: constant literals need neither be pooled, nor be in the code-segment, nor need they be in any type of read-only section. On systems with memory-protection or read-only memory they will be put there when possible by most compilers per default, sure, but that's not contractual.
@Dogbert: Well, the best documentation for that is actually the standard. If you want a good post here which explicitly handles that, look at this answer: stackoverflow.com/a/4105123
|
1

Because word is a pointer to a constant (read-only) characters sequence. In other words, you can't change the contents of a string literal.

If you want to change its contents, you should declare word as an array of chars:

char word[]="aacdbc";

With that small change, the segfault should disappear.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.