P
P
Pinkman2020-07-23 22:30:07
C++ / C#
Pinkman, 2020-07-23 22:30:07

Why doesn't it reverse the string?

Good evening! Help me understand what the error is ...
There is such a code:

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

char	*ft_strrev(char *str)
{
  char tmp;
  int start_len;
  int end_len;

  start_len = 0;
  end_len = 0;
  while (str[end_len])
    end_len++;
  end_len -= 1;
  while (start_len <= end_len)
  {
    tmp = str[end_len];
    str[end_len] = str[start_len];
    str[start_len] = tmp;
    start_len++;
    end_len--;
  }
  return (str);
}

int		main(void)
{
  char *str = "hello";
  ft_strrev(str);
  printf("%s", str);
  return (0);
}

As a result, I get an error SIGSEGV
gdb says that the error crashes on the first iteration on the line:
str[end_len] = str[start_len];
What's wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2020-07-23
@famousman204

What's wrong?
char *str = "hello";

This line is wrong. The fact that the compiler allows you to do this is an anachronism and the absence of even the slightest diagnostic. "hello" can be (and in your case seems to be) in a read-only area of ​​memory, you cannot change this string. It would be correct to write like this:
char str[] = "hello";
If you make this replacement, then the code will allocate space for the str array on the stack, you can change such an array.

E
Evgeny Zaletsky, 2020-07-23
@JZ_52

#include <iostream>
#include <string>
#include <algorithm>
 
int main()
{
   std::string str = "test string";
   
   std::reverse(str.begin(), str.end());
   
   std::cout << str << std::endl;
 
   return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question