Kookerus
Kookerus

Reputation: 546

Looping Over a String Gives Segmentation Fault

I'm writing a function to make a string lowercase in C++. It works perfectly fine, but after the last character, it gives a segmentation fault. My code is below:

#include <cctype>
#include <string>
#include <iostream>
using namespace std;

string lowercase(string str)
{
    string ans = str;
    for (int i=0; i < ans.size(); i++)
    {
        ans[i] = tolower(ans[i]);
        cout << ans[i]<<endl;
    }
}

int main()
{
    lowercase("TEST");
    return 0;
}

What should I do to fix this?

Upvotes: 0

Views: 153

Answers (1)

Trevor Hickey
Trevor Hickey

Reputation: 37894

Turning on the warnings, you may spot the error yourself:

g++ -o main main.cpp -Wall  

Errors:

main.cpp: In function ‘std::string lowercase(std::string)’:
main.cpp:9:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for (int i=0; i < ans.size(); i++)
                     ^
main.cpp:14:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }

Your function returns a string, but you have not specified a string to return.
You can fix the problem by returning your ans variable:

 string lowercase(string str)
{
    string ans = str;
    for (int i=0; i < ans.size(); i++)
    {
        ans[i] = tolower(ans[i]);
        cout << ans[i]<<endl;
    }
    return ans;
}  

Upvotes: 3

Related Questions