-1

I need the getline() function for some white space, including text input by the user. But instead of the user input, I get a segmentation fault.

Here is a minimized example:

#include <iostream>
#include <string>
#include <ctime>

/**
 * Shows main menu.
 *
 * @version 1.0.0
 *
 * @return Returns selected option.
 */
unsigned int showMenu() {
    unsigned int result;
    printf("\n\nSimple transfer\n===============\n\n");
    printf("Options:\n-----------\n");
    printf(" 1: Receive\n");
    printf(" 2: Send\n");
    printf("Enter any other number to exit.\n\n");
    printf("?: ");
    scanf("%u", &result);
    return result;
}

// Some functions.

/**
 * Entry point.
 *
 * @version 1.2.0
 *
 * @return Returns result code.
 */
int main() {
    // Initialization.
    setbuf(stdout, NULL);
    bool expectData;
    std::string inMessage, outMessage;
    // Run.
    while (true) {
        switch (showMenu()) {
            // Receiving mode.
            case 1:
                // Some code.
                std::cout << "Received.\n";
                break;

            // Sending mode.
            case 2:
                outMessage = "Dies ist eine Testnachricht.";
                getline(std::cin, outMessage);
                printf("Sending: ");
                for (unsigned int i = 0; i <= outMessage.length() -1; i++) {
                    // Some code.
                    printf("%c", outMessage[i]);
                }
                printf("\n");
                break;

            // Exit.
            default:
                printf("Bye.\n");
                return 0;
        }
    }
}

What is the reason and how can I fix it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sukombu
  • 157
  • 3
  • 12
  • Why are you initializing outMessage and then reading into it? What is the input that breaks the program? – nicomp Jan 11 '20 at 18:16
  • 3
    Why are you using `printf` and `scanf` in C++ code? You aren't even consistent, since you are mixing it with use of the C++ IO library. – walnut Jan 11 '20 at 18:17
  • Always check the return value of scanf. See [this link](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) for further information. Also, you may want to use a debugger to find out where exactly your program is crashing. – Andreas Wenzel Jan 11 '20 at 18:17
  • 2
    Read [*How to debug small programs*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and more about [C++](https://en.cppreference.com/w/cpp) and [about GCC](https://gcc.gnu.org/onlinedocs/gcc/) (which includes `g++`) and [`gdb`](http://sourceware.org/gdb/current/onlinedocs/gdb/). Compile with `g++ -Wall -Wextra -g` – Basile Starynkevitch Jan 11 '20 at 18:35
  • 1
    Segmentation faults are beautiful. Especially compared to the alternative of the program silently corrupting memory. – user4581301 Jan 11 '20 at 18:50
  • This doesn't address the question, but `i <= outMessage.length() -1` is usually written `i < outMessage.length() `. – Pete Becker Jan 11 '20 at 19:05
  • `setbuf(stdout, NULL);` Why? – Lightness Races in Orbit Jan 11 '20 at 19:25
  • @nicomp Just for testing. – Sukombu Jan 11 '20 at 19:42
  • @LightnessRacesBY-SA3.0 This is because some of the code, i removed at this example, uses printf() and should write it letter by letter instead of waiting. – Sukombu Jan 11 '20 at 22:14
  • 1
    Ok so that line should have been removed from the [mcve] to narrow it down – Lightness Races in Orbit Jan 11 '20 at 22:15

1 Answers1

3

You have to use:

std::cin.ignore();

Before your getline(...);, because it is reading your new line character caused by hitting enter instead of letting you type the message. See this question for more details.

You are getting Expression: string subscript out of range exception, because you are trying to subscript an empty string here: printf("%c", outMessage[i]);

EDIT: As @Johnny Mopp pointed out in the comment, outMessage.length() is returning size_t type, which is unsigned type. Then from unsigned 0 you are subtracting 1, overflowing it to a 'big' number, so the for loop tries to print the very long non-existent string.

Hawky
  • 441
  • 1
  • 3
  • 10