Easy Question - new to programming

Discussion in 'Mac Programming' started by cjmac19, Apr 18, 2013.

  1. cjmac19, Apr 18, 2013
    Last edited by a moderator: Apr 18, 2013

    macrumors newbie

    Apr 18, 2013
    I wrote the following code, a simple string test and I get an error message every time I run it saying "Hey(5031) malloc: *** error for object 0x1000041c0: pointer being freed was not allocated
    *** set a breakpoint in malloc_error_break to debug
    Abort trap"

    How do I fix this?

    #include <iostream>
    #include <string>
    using namespace std;
    int main ()
    	string user_first_name;
    	string user_last_name;
    	cout << "First name: ";
    	cin >> user_first_name;
    	cout << "Last name: ";
    	cin >> user_last_name
    	string user_full_name = user_first_name + " " + user_last_name;
    	cout << "Your name is " << user_full_name << "\n";
  2. macrumors member

    Jun 4, 2009
    I haven't done c++ in a while (thankfully!) but the code looks OK to me (apart from a missing ";" ). I don't see any problems when I run the code either. How are you compiling it? I just used clang++ -Wall blah.cpp.

    /me now waits for the more regular C++ users to point out what we both missed.

  3. macrumors 6502

    Mar 12, 2010
    Since you couldn't have actually compiled the code you posted as it's missing a semicolon, my guess is your error is from something else.

    If you were to get that code to compile it would run fine.
  4. macrumors 68040


    Jan 10, 2005
    Dallas, TX
  5. macrumors 604


    Nov 26, 2007
    I wasn't aware of + working on strings without the user implementing it themselves in C++... I thought you had to use a bunch of << into a string buffer and then use the string function to convert that buffer to a new string if you wanted to concatenate strings?
  6. ytk
    macrumors regular

    Jul 8, 2010
    Well, why not give it a try and see if you're right or not? :rolleyes:
  7. macrumors G5


    Nov 25, 2005
    You can. operator+ is implemented, and there is automatic conversion from C string to std::string. You have to be awfully careful. For example

    std::string x = "3";
    std::string y = "1" + 2 + x;

    will compile just fine, but will most likely crash. If you think hard enough about it you'll know why. While

    std::string z = x + 2 + "1"; will not compile (I think it won't. If it does it will work).

    There are other methods like "append", I think "replace", that are quite useful.
  8. macrumors 6502a

    May 10, 2009
    Des Moines, WA
    The code is good it compiles and run just fine for me!

    Do you have any other issues with your computer?
    What is the size and free space available on the hard disk of your computer?
    How much RAM do you have?

Share This Page