0
            #include <stdio.h>

            void reverse(char *st, int length);
            int strl(char *str);

            int main (void)
            {                    

// here if str is an array the code will work

                char *str = "future video";
                printf("%s\n", str);
                reverse(str, strl(str));
                printf("%s\n", str);
            }

This is a function for counting the length of the string

            int strl(char *str)
            {
                int offset = 0;
                while (str[offset] != 0)
                {
                    offset++;
                }
                return offset;
            }

This is a function to reverse the string

            void reverse(char *st, int length)
            {
                char tmp;
                for (int i = 0; i < length / 2; i++)
                {
                    tmp = st[i];

 

//I used gdb and the seg fault happens in this line

                    st[i] = st[length-1-i];
                    st[length-1-i] = tmp;
                }
            }
youkum
  • 1
  • 1
  • 1
    This string literal is allocated to read-only memory: `char *str = "future video";`. Look here for more details: [Why are C string literals read-only?](https://softwareengineering.stackexchange.com/questions/294748/why-are-c-string-literals-read-only/294750) – paulsm4 Aug 04 '21 at 18:17
  • When you declare `str` as an array `char str[] = "future video";`, the array is placed into **writable** memory, and the string literal is copied into the array. – user3386109 Aug 04 '21 at 18:23
  • **I am voting to reopen the question because** [the alleged duplicate question](https://stackoverflow.com/questions/690176/c-c-optimization-of-pointers-to-string-constants) is not about the read-only nature of string literals in general, but is specific to merging string literals. Also, the alleged duplicate question is C++, not C, and the question makes several uses of C++ features that do not exist in C. In my opinion, [this question](https://stackoverflow.com/q/1011455/12149471) would be a more appropriate duplicate. – Andreas Wenzel Aug 09 '21 at 14:42

0 Answers0