Click here to Skip to main content
15,393,377 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I am learning C language and suffice to say I am just a beginner(especially in pointers and memory allocation). I have written the below function for reversing an string using C language, but it shows segmentaion fault excpetion when it arrives at the second line in for loop. I have read a bit about segmentation fault. For example in this link, but actually I can't really understand why?!

I think that it's a complicated exception and I can't comprehend its reason completely.

Here are my functions:
C++
int get_string_length_using_pointer(char* input)
{
    int len = 0;
    // input changes in every iteration, because the pointer is changing
    // it could be also written as *(input++) 
    // but *input + 1 only shows tha ASCII code(it does not show the next character ASCII code of input)
    while (*input++)
    {
        len++;
    }
    return len;
}


C++
void reverse_string_using_pointer(char* input)
{
    char* begin_pointer;
    char* end_pointer;
    char tmp;
    int len = get_string_length_using_pointer(input);

    begin_pointer = input;
    end_pointer = input;
    // it needs also a (-1) for th upper bound becuase in the first time it is input[0]
    for (int i = 0; i < len - 1; i++)
    {
        end_pointer++;
    }

    for (int i = 0; i < len / 2; i++)
    {
        tmp = *end_pointer;
        *end_pointer = *begin_pointer;
        *begin_pointer = tmp;

        begin_pointer++;
        end_pointer--;
    }
}


and in main:
C++
int main(int argc, char** argv)
{
    // ///////////////////////////////////////////////////////
    char* sample2 = (char*)"Life is beautiful.";
    reverse_string_using_pointer(sample2);
}


What I have tried:

I have written NULL infront of both begin_pointer and end_pointer but after deleting this part, it still shows the error.

I will be grateful for any help and advice.
Posted
Updated 10-Dec-21 9:38am
v2
Comments
k5054 10-Dec-21 18:03pm
   
Unless you've got a good reason not to, you should probably stick with strlen(), rather than writing your own - especially if you're dealing with long strings. Your system supplied strlen will probably make use of assembler instructions that will greatly improve performance. For example, on my home PC calling your get_string_length_from_pointer() on a 5MB string takes about 60 times as long as calling the system provided strlen(). That's without any optimization, but even turning on full optimization, strlen() still outperforms by a factor of about 9:1. The same will be true of other string functions in the string library.

The problem here is the nature of the string you are attempting to reverse. That is stored in a read-only section of your program's memory so you can not modify it. The segment fault results when you do. The way to fix it is to make a local buffer to use. Here is one way you can do this :
C
int main(int argc, char** argv)
{
    char* sample2 = "Life is beautiful.";
    char buffer[ 256 ];   // way bigger than necessary but that's OK
    strcpy( buffer, sample2 );   // copy the string to the buffer
    reverse_string_using_pointer( buffer );
}
One other thing - you have the length of the string so you don't to loop through it to find the end because you already know where that is. This is how you can assign the pointer to it directly :
C
int len = get_string_length_using_pointer( input );

begin_pointer = input;
end_pointer = input[ len - 1 ];
As you (should) know, array indexes begin with zero so if a string is eight characters long then index seven is the last character of the string.
   
Comments
Aylin Naebzadeh 10-Dec-21 16:15pm
   
Thanks🙏. I thought it is no difference between a char* or a char[].
Rick York 10-Dec-21 17:01pm
   
There is no difference between them but that's not issue with your code. The issue is you can not modify read-only memory.
Aylin Naebzadeh 10-Dec-21 23:58pm
   
But why the problem has been solved after I pass the parameter of my function as a char[]? Does it mean that a char[] is not read-only like char*?Thanks.
Rick York 11-Dec-21 12:58pm
   
Your problem was that you can not modify the memory you passed to the function - it was read-only or constant. The revised code passes memory that IS modifiable or non-constant.
Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C
int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary.
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
   
Comments
Aylin Naebzadeh 10-Dec-21 15:59pm
   
Thank you for your advice.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900