Search code examples
c++stringreplacelowercase

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?


Solution

  • 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;
    }