Ryan
Ryan

Reputation: 21

What is wrong with my C++ code involving a function calling another function?

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

// function prototypes
string boxOfStars(int w, int h);
string lineOfStars(int len);

// function definitions
string lineOfStars(int len) {
    string result = "";
    for (int j=0; j<len; j++) {
        result += "*";
    }
    return result;
}

string boxOfStars(int w, int h) {
    string result_1 = lineOfStars(w);
    for (int i=0; i<h; i++)
        cout << result_1 << endl;

    return 0;
}

int main() {

    int width, length;

    cout << ""Enter a width and length: ";
    cin >> width >> length;
    cout << boxOfStars(width, length);

    return 0;
}

The point of this program is to call the lineOfStars() function within the boxOfStars() function.

When I run the program, I get a "Segmentation fault: 11" error.

Enter a width and length: 5 5
*****
*****
*****
*****
*****
Segmentation fault: 11

I have tried searching for this all over the internet, but cannot seem to find the issue.

The program runs fine in the terminal, but at the end of each output, I get this error message.

Can someone please explain to me the fault in my code?

Upvotes: 0

Views: 47

Answers (3)

When you do

string boxOfStars(int w, int h) {
    /* ... */
    return 0;
}

you're trying to return 0 and you say it returns a string. So the compiler adds a conversion to string for you, the same as you wrote this:

string boxOfStars(int w, int h) {
    /* ... */
    return (string)0;
}

Specifically in this case, 0 is interpreted as a null pointer, and it will call the constructor that creates a string from a const char *. Trying to access the null pointer (to read the string) causes the segfault. Oops!

Upvotes: 0

kmdreko
kmdreko

Reputation: 59827

boxOfStars() has a return type of std::string, but it is returning 0, which gets interpreted as a null char* pointer. Passing a null char* pointer to the std::string constructor is undefined behavior.

You probably want boxOfStars() to return void instead, and not have the cout << boxOfStars(...) in your main().

Upvotes: 4

Jay
Jay

Reputation: 656

You are attempting to cout the result of BoxOfStars, which is 0. The function BoxOfStars itself is doing the cout for the stars. Seems you have doubled-up code a bit.

Upvotes: 0

Related Questions