Thread: String assignment segmentation fault (core dump)

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    134

    String assignment segmentation fault (core dump)

    Please solve this issue, you can run this program.. its complete

    Code:
    #include<iostream>
    #include<cstdlib>
    #include<string>
    
    using namespace std;
    
    struct node 
    {
            string name;
            int i;
    };
    
    int main(int argc, char *argv[])
    {
            struct node *first;
            first = (struct node *) malloc(sizeof(struct node));
            first->name ="Hi there";
            cout << first->i;
    
    }

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Why use malloc? Use new as you wont be calling constructors for std::string without it.

    Dont forget to call delete also

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Don't use malloc() to create "first" in main(). Use operator new instead.

    Also initialise first->i to a valid value before trying to print it.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    May 2008
    Posts
    134

    How to use new in this context?

    Can you tell me the exact code to use the new for this?

    and make me clear why this is throwing segmentation fault(core dump)?
    I don't this this is happening for malloc?

  5. #5
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Look it up in the faq - Cprogramming.com FAQ > Dynamic Memory Allocation: new and delete (C++)

    The problem is likely to be that malloc is not calling the constructor on the string object in your struct, so the use of the object is risky to say the least

  6. #6
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by kapil1089thekin View Post
    Can you tell me the exact code to use the new for this?

    and make me clear why this is throwing segmentation fault(core dump)?
    I don't this this is happening for malloc?
    Again, 'malloc' just allocates a chunk of memory, whereas 'new' allocates and then invokes the constructor on the object (and in turn, it's sub-objects). The 'string' object in your code isn't properly initialized by it's constructor, so its state is indeterminate.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  7. #7
    Registered User
    Join Date
    May 2008
    Posts
    134

    structure use in C++ good practice?

    Is it good practice to use in c++? or there is a better way let me know, actually I am good in c but may be intermediate in c++, most of the time I cant find the diffrence between them and so I use c codes, how to know more using c++ features and diffrentiate between the c++ and C coding, I would also appreciate the notion of good coding practice in c++

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well I looked at your code in the debugger, and the string object was garbage just after calling malloc.

    If anything you're allocating space for has a C++ class in it, then you MUST use new to allocate the space for it, so that the class constructor can be called.

    If you don't, then the class instance contains garbage and you most likely crash as a result.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Registered User
    Join Date
    May 2008
    Posts
    134

    didn't get the precise answer

    Is it good to use structure in C++?
    and how to use new here in my code to make it work?
    just make the necessary changes and post the code, thanks in advance.

  10. #10
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by kapil1089thekin View Post
    Is it good to use structure in C++?
    If it makes more sense to use a C-style struct in a given situation, go right ahead.

    Quote Originally Posted by kapil1089thekin View Post
    and how to use new here in my code to make it work?
    just make the necessary changes and post the code, thanks in advance.
    See here.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  11. #11
    Registered User
    Join Date
    Jul 2010
    Location
    Oklahoma
    Posts
    107
    Kapil,

    The other posters are suggesting using 'new' rather than just getting a piece of memory from the heap with 'malloc.' The rationale is that the new operator triggers the constructor of composite (or aggregated) datatypes, like your struct in this example. To provide a precise answer, this is a known solution:

    Code:
    #include<iostream>
    #include<cstdlib>
    #include<string>
    
    using namespace std;
    
    struct node 
    {
            string name;
            int i;
    };
    
    int main(int argc, char *argv[])
    {
            struct node *first;
            first = new struct node;
            first->name ="Hi there";
            cout << first->i;
    
    }
    The output I received when I used Dev-C++ in Windows is "0," then I modified it to print the string which had been assigned to name. This was also successful. I was trying to recall if there was a way to call the string member's constructor manually once it had been allocated by malloc...but I don't recall one at the moment.


    Best Regards,

    New Ink -- Henry

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by new_ink2001
    To provide a precise answer, this is a known solution:
    As Salem noted, there should be a corresponding delete. One can also write node instead of struct node despite the lack of a typedef since this is C++.

    Quote Originally Posted by new_ink2001
    I was trying to recall if there was a way to call the string member's constructor manually once it had been allocated by malloc...but I don't recall one at the moment.
    Under different circumstances, placement new would be an option to construct a node object at the allocated memory, but I would not suggest it here. In fact, I would not even suggest dynamic memory allocation here to begin with, but presumably kapil1089thekin was just experimenting.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by new_ink2001 View Post
    I was trying to recall if there was a way to call the string member's constructor manually once it had been allocated by malloc...but I don't recall one at the moment.
    It's called "placement new", and it should be used only in very special cases.

    Code:
    #include <string>
    #include <iostream>
    
    int main( void )
    {
        using namespace std;
        string* str = static_cast< string* >( malloc( sizeof( string ) ) );
    /*
        Manually invoke the constructor.
    */    
        new ( str ) string( "Hello World!" );
        cout << *str << endl;
    /*
        We can't use 'delete' because it may not be compatible with the result of our 
        'malloc' call, so we have to invoke the destructor and 'free' the memory manually. 
    */    
        str->~string( );
        free( str );
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  14. #14
    Registered User
    Join Date
    May 2008
    Posts
    134

    thanks all

    Thank you all posters, I am immensely satisfied with your answer, but knowing new things is the best pleasure I can have, so I am asking again a qn which may sound vacuous to all of you,

    1.Do I need to delete each node in a linked list if I get each node'e memory allocation by calling new?

    2. In that case it will add O(n) time complexity more? right?

    3.Is there any better solution for freeing the memory?

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by kapil1089thekin
    1.Do I need to delete each node in a linked list if I get each node'e memory allocation by calling new?
    Yes, you should.

    Quote Originally Posted by kapil1089thekin
    2. In that case it will add O(n) time complexity more? right?
    Yes.

    Quote Originally Posted by kapil1089thekin
    3.Is there any better solution for freeing the memory?
    No. There is a minimum amount of work to be done for anything, and in the case of destroying a linked list of n nodes, this is it.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polymorphism and generic lists
    By Shibby3 in forum C# Programming
    Replies: 9
    Last Post: 07-26-2010, 05:27 AM
  2. Segmentation fault when changing a string
    By lilydjwg in forum C Programming
    Replies: 6
    Last Post: 12-02-2009, 07:43 AM
  3. segmentation fault... first time with unix...
    By theMethod in forum C Programming
    Replies: 16
    Last Post: 09-30-2008, 02:01 AM
  4. segmentation core dump - need help
    By knight101 in forum C++ Programming
    Replies: 1
    Last Post: 11-26-2001, 04:43 PM