Thread: Delete object created in the function

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    16

    Delete object created in the function

    Hi ,

    I'm a beginner at C++ and I've created a code in order to reverse statement and gets vowels from it. it's an exercise.
    In the getVowels function I've allocated an array in order to fill it with found vowels and return the stream to main().
    I know that dynamic memory is resident on Heap therefore it isn't a local storage.
    How do I free the memory ?Where I have to insert delete[] ?

    Code:
    #include "pch.h"
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    string reverse(string str);
    string getVowels(string str);
    
    int main()
    {
    
        string statement = "The best is yet to come";
    
        string reversed;
        string vowels;
        
        std::cout << "Hello World!\n";
        cout << "Statement: " << statement << endl;
    
        reversed = reverse(statement);
        cout << "Reversed: " << reversed << endl;
        
        vowels = getVowels(reversed);
        cout << "Vowels: " << vowels << endl;
    
            
        return 0;
    }
    string getVowels(string statement) {
        
        char vowels[] = { 'a','e','i','o','u' };
        int len = statement.size();
        int cont = 0;
    
        char *foundVowels = NULL;      
        foundVowels = new char[len]; // Allocated space like statement lengh
    
        cout << "\nSize: " << len << endl;
           
        for (char c : statement) {
    
            for (char vowelsList : vowels) {
    
                if (vowelsList == c) {
                    foundVowels[cont++] = c;
                    // cout << vocale << " " << carattere << " " << cont << endl; // debug
                }
            }
        
        }
    
        foundVowels[cont] = '\0'; // clean string
         
        return foundVowels;
    
    }
    string reverse(string statement)
    {
        int len = statement.size();
        string invertiStr = statement;
    
        cout << "\nSize: " << len << endl;
    
        for (char c : statement)
        {
            invertiStr[--len] = c;
            //cout << c << " " << len << endl; //debug
        }
        return invertiStr;
    }
    The solution has been to add a new string in the local function and
    copy on it the result from foundvowvels[] :

    Code:
    string result;
    
    ...............................
    result = foundVowels[cont];
    
    delete[] foundVowels;
    
    return result;
    might I ask to you if that is a good practice or I've got a bad idea ?

    Thanks
    Last edited by Lag; 03-31-2019 at 09:03 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,686
    Well making a string result is the way to go in your code at the moment.

    > foundVowels = new char[len];
    But your code is broken if the input is all vowels.
    You're one short on the amount of space you need.

    Since you could also do
    string result;

    then later append characters to your result
    result += c;

    The whole messy manual memory management (and the risk of getting it wrong) goes away.
    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.

  3. #3
    Registered User
    Join Date
    Mar 2019
    Posts
    16
    Hi
    it works great.
    There is no problem with object and even less with Heap corruption

    Thanks a lot
    Code:
    string getVowels(string statement) {
        
        char vowels[] = { 'a','e','i','o','u' };
        int len = statement.size();
        string result;
    
        cout << "\nSize: " << len << endl;
           
        for (char c : statement) {
            for (char vowelsList : vowels) {
                if (vowelsList == c) {
                    result += c;
                    cout << vowelsList << " " << c << endl; // debug
                }
            }
        }
        
        return result;
    }

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,515
    You should be aware that in terms of naming, this doesn't make sense:
    Code:
    for (char vowelsList : vowels) {
    vowels forms the range that you're iterating over, which means that vowelsList is a vowel, not a list of vowels, so you should have named it vowel.

    Instead of directly looping over the vowels, I would have stored them in a string that could be searched:
    Code:
    string getVowels(const string& statement) {
        const string vowels = "aeiou";
    
        string result;
        for (char c : statement) {
            if (vowels.find(c) != string::npos) {
                result += c;
            }
        }
        return result;
    }
    Notice that I have made statement a const reference since you don't need a copy of the statement from the caller, and you don't need move semantics.

    If you were feeling more adventurous, you could #include <algorithm> and replace even that remaining loop:
    Code:
    copy_if(statement.begin(), statement.end(), back_inserter(result),
            [&vowels](char c) { return vowels.find(c) != string::npos; });
    EDIT:
    There is yet another way, but it is fundamentally different from your approach, but perhaps it is good to keep in mind. What you did, and what I showed you, are variations on the theme of "copy vowels from the source to the result". This other way is "remove non-vowels from a copy of the source to become the result":
    Code:
    string getVowels(string statement) {
        const string vowels = "aeiou";
    
        statement.erase(
            remove_if(statement.begin(), statement.end(),
                      [&vowels](char c) { return vowels.find(c) == string::npos; }),
            statement.end()
        );
        return statement;
    }
    You would see that I have changed the function parameter back to string so that a copy is made, and then use the remove_if algorithm to "remove" the characters of statement in-place such that all the non-vowels are at the end. Then, I call statement's erase member function to erase the "removed" characters, leaving the vowels that are then returned.
    Last edited by laserlight; 03-31-2019 at 04:33 PM.
    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

  5. #5
    Registered User
    Join Date
    Mar 2019
    Posts
    16
    Hello Laserlight, thank you for your kind remark.
    I 've understood and I'm going to update the code with your solutions.

    Note:
    by string.find() is very easy achieve the same result. It makes the c++ look a very high level language

    I couldnt identify
    Code:
     statement.erase() 
    .
    I have searched for it here :
    remove_if - C++ Reference
    and I didn't find "erase", may be I understand remove_if syntax , but not erase.
    I think it's a bit advanced and I should postpone that topic

  6. #6
    Registered User
    Join Date
    Mar 2019
    Posts
    16
    I 've understood and I'm going to update the code.

    string.find() is great it makes c++ look a very high level language

    I've found "remove_if" syntax , but i don't know what "erase" means or where I can read about it.
    May be it's an advanced topic and I should postpone it.

    Thanks
    Last edited by Lag; 04-03-2019 at 08:43 AM.

  7. #7
    Registered User
    Join Date
    May 2009
    Posts
    3,749
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  8. #8
    Registered User
    Join Date
    Mar 2019
    Posts
    16
    Thanks

  9. #9
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    How were you able to color your code in that way?

  10. #10
    Registered User
    Join Date
    Mar 2019
    Posts
    16
    Quote Originally Posted by Nwb View Post
    How were you able to color your code in that way?

    I'm sorry. I didn't notice much.
    I retry:

    Go Advanced
    Use CODE TAG
    copy paste from Visual Studio

    Code:
           string statement = "The best is yet to come";
    
        string reversed;
        string vowels;
    
    
        std::cout << "Hello World!\n";
        cout << "Statement: " << statement << endl;
    
    
        reversed = reverse(statement);
        cout << "Reversed: " << reversed << endl;
    
    
        vowels = getVowels(reversed);
        cout << "Vowels: " << vowels << endl;
    Edit:
    no color
    Last edited by Lag; 04-04-2019 at 10:24 AM.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,686
    > How were you able to color your code in that way?
    You shouldn't.

    99% of the time, when people copy/paste marked-up code (ie, includes font/colour tags), the result on the forum is a horrible mess.

    Just copy-as-text / paste-as-text and the board will do just fine.
    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.

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    3,749
    To see the color after pasting as text; I often have to refresh the page.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  13. #13
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    Can you copy from Visual Studio with the color though? I thought you could only copy text. How might OP have done that? Weird..?

    Tim I'm referring to OP's original topic post, do you notice that the text itself is colored?

  14. #14
    Registered User
    Join Date
    May 2009
    Posts
    3,749
    Quote Originally Posted by Nwb View Post
    Can you copy from Visual Studio with the color though? I thought you could only copy text. How might OP have done that? Weird..?

    Tim I'm referring to OP's original topic post, do you notice that the text itself is colored?
    To see how that did the stupid thing do reply with quote.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  15. #15
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    Yes I saw that the text is formatted. But how does he copy the formatting as well?
    I use Visual Studio too.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 12-19-2015, 06:04 AM
  2. Temporary object created by calling constructor
    By Eman in forum C++ Programming
    Replies: 18
    Last Post: 12-21-2010, 01:19 PM
  3. Replies: 2
    Last Post: 02-26-2009, 11:48 PM
  4. delete object from inside object
    By Drogin in forum C++ Programming
    Replies: 10
    Last Post: 01-02-2009, 08:55 PM
  5. Replies: 13
    Last Post: 04-29-2002, 11:06 PM

Tags for this Thread