0

I've got a character from the keyboard, by integer:

int c = getch();

an I want to append it to a string only if it isn't a return:

void somefunction()
{
    std::string str = "you pressed: ";
    int c;
    while ( 1 )
    {
        c = getch();
        if ( c == 10 ) break;
        char* ch;
        sprintf(ch,"%c",c);
        str += std::string(ch);
    }
}

however, this creates a segmentation error when the scope of somefunction is left. I'm geussing that when the dtor for str is called the pointer to ch isn't available any more.

How can I remedy this?

5
  • 3
    Your problem here is that the pointer ch is not initialized and could point anywhere. Commented Jun 12, 2012 at 11:38
  • The segmentation error happens because you don't actually allocate any memory for character array sprintf prints to. Commented Jun 12, 2012 at 11:39
  • Your other problem is that you are mixing C style string manipulation with C++ style thereof. This can be done, of course, but isn't necessary and non-trivial to get right (as indicated by sstn). Commented Jun 12, 2012 at 11:39
  • The segfault is because sprintf is writing into random data. Change char *ch; to char ch[2]; - but really, use any of the proper std::string methods in the answers... Commented Jun 12, 2012 at 11:39
  • the strange thing is that when I comment out the str += ... line, no segfault occurs, leading me to believe the ch initialisation is done properly. Commented Jun 12, 2012 at 11:49

2 Answers 2

13

This is much easier than you think:

str.push_back(c);
Sign up to request clarification or add additional context in comments.

3 Comments

@Nawaz What makes you say that?
@JamesMcLaughlin: Ohh... I mistakenly thought it as + rather than +=.
stringstream could be another class of interest here.
7

You are getting segmentation fault, because you are trying to sprintf string into unknown (not yet allocated) memory:

char* ch;
sprintf(ch,"%c",c);

possible fix of your code would be to replace char* ch; with char ch[2]; which would cause ch to become an statically allocated array with an automatic storage duration.

But note that since you are programming in C++ it would be wiser to use streams and methods of std::string rather than C-style (char*) strings and C-style functions like sprintf.

1 Comment

+1. Actually it is a complete answer, as it explains the cause of the segfault.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.