segfault in pointer to string program

hello all,
my question is not about How code can be rewritten, i just wanna know even though i am not using read only memory of C (i have declared str[20]) why this function gives me segfault :wall:and the other code executes comfortably though both code uses same pointer arithmetic.

#include<stdio.h>
#include<string.h>
void reverse(char*);
int
main()
{
 char str[20];

 scanf("%s",str);
 printf("original string is %s :\n",str);
 reverse(str);
 printf("reverse string is %s  :",str);
 return 0;
}

void reverse(char* s)
{
 int n,mark,temp;
 n = mark = strlen(s);

 for(;s < (s + n/2);++s)
    {
      temp = *s;
      *s = *(s + (--mark));
      *(s + mark) = temp;
    }

 return;
}

while the code below executes happily

void my_strrev(char* begin){
    char temp;
    char* end;
    end = begin + strlen(begin)-1;

    while(end>begin){
        temp = *end;
        *end = *begin;
        *begin = temp;
        end--;
        begin++;
    } 
}

main(){
    char string[20];
    scanf("%s",string);
    my_strrev(string);
    printf("%s", string);
}

This loop never ends, you just walk right off the end of the string:

 for(;s < (s + n/2);++s)

n is a constant value, you keep incrementing s, and off you go.

1 Like

got it :smiley: thank you so much. do C through segfault for any particular type of error?? i wanna know when exactly C throws segfault?

segfault is one kind of runtime error and there can be a number of reasons for it...the most common ones are buffer overruns or stepping into memory which is read only or dereferencing an invalid address pointer.

1 Like

All 'segfault' means is that your program attempted to access a memory page that either
1) doesn't exist, or
2) your program doesn't have permissions to access.

There's almost endless reasons why a program could end up doing that but it's often a logic error of some sort -- not checking the return value of something and dereferencing a NULL, going beyond array bounds and accidentally overwriting nearby variables, reusing a pointer you already free()'d and mangling whatever data(if anything) ended up in it later... You can even corrupt the stack frame itself so return jumps the program to invalid memory and bombs out long after the actual error was made. And lots more.

You went beyond array bounds, which would have started modifying the values of local stack variables. This can go wrong in many interesting ways... it could have kept going until you'd mangled your entire stack and hit the bottom of memory. Or (more likely) when you started mangling local stack variables, the value of s was set to some bizzare value which pointed to invalid memory.

1 Like