-2

I am new in C and am encountering some issues. Im trying to reverse a given string in C and somehow get a segmentation fault while doing it

#include <stdio.h>
#include "my_revstr.h"


int my_strlen(char const str[]){
        int i = 0;
        int count = 0;
        while (str[i] != '\0'){
                count++;
                i++;
}
        return count;
}
void my_revstr(char str[]) {


        int len = my_strlen(str);
        char temp;
        char* ptr = str;
        char test;
        for (int i = 0 ; i < len /2; i++) {
                ptr +=  ptr[i];
                str[i]= str[(len/2)-1];
}
        printf("%s", str);
}
int main() {
        my_revstr("ABCDE");
}

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

1

For starters you may not change a string literal.

my_revstr("ABCDE");

Any attempt to change a string literal results in undefined behavior.

You need to declare a character array initialized by the string literal and pass it to the function

For example

char s[] = "ABCDE"; 
my_revstr( s );

Nevertheless in any case your function my_revstr does not make a sense.

All it does is changing the first half of a string due to this statement

str[i]= str[(len/2)-1];

Moreover this statement

ptr +=  ptr[i];

can invoke undefined behavior.

Your functions can look the following way

size_t my_strlen( const char *s )
{
    size_t n = 0;

    while ( s[n] ) ++n;

    return n;
}

char * my_revstr( char *s ) 
{
    for ( size_t i = 0, n = my_strlen( s ); i < n / 2; i++ )
    {
        char c = s[i];
        s[i] = s[n - i - 1];
        s[n - i - 1] = c;
    }

    return s;
}

And in main you can write

int main( void ) 
{
    char s[] = "ABCDE";
    
    puts( s );
    puts( my_revstr( s ) );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335