CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Oct 2010
    Posts
    98

    [RESOLVED] allocating and deallocating

    hi all,

    my following program is not working, can anyone please tell me what's wrong with that?

    Code:
    class Example   
    {
    private:
           char *name;
    public:
          Example()
          {
               name = new char[20];
          }
          ~Example()
          {
               delete[] name;
          }
         
          Example(const Example &b)
          {
               name = new char[20];
               strcpy(name, b.name);
          }
    	  void setName(char* n)
    	  {
    				name=n;
    	  }
          char* getName()
    	  {
    			   return name;
    	  }
    };
    int main()
    {
    
    Example b;
    	char* n=NULL;
    	cin>>n;
    	b.setName(n);
    	cout<<b.getName();
    return 0;
    }

  2. #2
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: allocating and deallocating

    How is it not working? Does it not compile? Does it crash? Does it not produce the output you expected?
    Also, did you step through your program using the debugger?
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  3. #3
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: allocating and deallocating

    Quote Originally Posted by Aashi View Post
    char* n=NULL;
    cin>>n;
    What did you expect to happen here? Since you use C++ why not use a std::string instead?
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  4. #4
    Join Date
    Oct 2010
    Posts
    98

    Re: allocating and deallocating

    Quote Originally Posted by D_Drmmr View Post
    How is it not working? Does it not compile? Does it crash? Does it not produce the output you expected?
    Also, did you step through your program using the debugger?
    it complies, takes input and then program crashes.

    Quote Originally Posted by S_M_A View Post
    What did you expect to happen here? Since you use C++ why not use a std::string instead?
    I know, but i want to use this for learning.

    please tell how can i make my program working? it crashes after taking input.

  5. #5
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: allocating and deallocating

    Where is cin supposed to store the input when you make n a NULL-pointer?
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  6. #6
    Join Date
    Apr 1999
    Posts
    27,449

    Re: allocating and deallocating

    Quote Originally Posted by Aashi View Post
    it complies, takes input and then program crashes.

    I know, but i want to use this for learning.
    Part of learning how to program is to know how to debug your own code. Just writing code and then dumping it here waiting for us to debug it is not the way you learn how to write a program. You must make the effort to debug your own code. You wrote it, you must be able to debug it.
    please tell how can i make my program working? it crashes after taking input.
    Can you at the very least identify which line causes the crash? Once you figure out which line it crashes on, look at that line and learn what could have happened. Use the debugger that comes with your compiler to step through the program.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; November 6th, 2011 at 08:31 AM.

  7. #7
    Join Date
    Nov 2011
    Posts
    1

    Re: allocating and deallocating

    Modifying these two lines....
    Code:
    	char* n=NULL;
    	cin>>n;
    like so...
    Code:
    	char n[256] = { '\0' };//Declares n to be a character array of length 256 and initializes all elements to terminating NULL character
    	cin.getline(n, 255);//Reads user input, ensuring that room remains for the terminating null character
    ... should get the program to run for you.

    The problem here is that you've declared n as a pointer to an array of characters but you never initialize it. If you do not declare the size of a character array at compile time, then you must either point it to some character array or dynamically allocate a new character array at run time before you can use it in any meaningful way. See this link for an excellent tutorial on pointers (the next chapter will talk about character arrays specifically), and the one after that, about dynamic memory allocation). You should come away from it understanding why what you're trying to do here doesn't work.

  8. #8
    Join Date
    Oct 2010
    Posts
    98

    Re: allocating and deallocating

    Quote Originally Posted by Paul McKenzie View Post
    Part of learning how to program is to know how to debug your own code. Just writing code and then dumping it here waiting for us to debug it is not the way you learn how to write a program. You must make the effort to debug your own code. You wrote it, you must be able to debug it.
    Can you at the very least identify which line causes the crash? Once you figure out which line it crashes on, look at that line and learn what could have happened. Use the debugger that comes with your compiler to step through the program.

    Regards,

    Paul McKenzie
    alright then, can you please tell me about how can i get input from user in a main using setter function?
    i'm not asking for code, here's my code with constructor and destructor where i'm dynamic allocating a char type indentifier. would be appreciated if you help me.
    Code:
    #include <iostream>
    using namespace std;
    
    class Example
    {
    private:
    	char* str;
    	int len;
    	static int num_strings;
    public:
    	Example(const char* s);
    	Example();
    	~Example();
    	void setName(char* n);
    	char* getName();
    	
    };
    int Example::num_strings=0;
    
    Example::Example(const char* s)
    {
    	len=strlen(s);
    	str=new char[len+1];
    	strcpy(str,s);
    	num_strings++;
    }
    Example::Example()
    {
    	len=4;
    	str=new char[4];
    	strcpy(str,"C++");
    	num_strings++;
    }
    Example::~Example()
    {
    	num_strings--;
    	delete[] str;
    }
    void Example::setName(char* n)
    {
    	strcpy(str,n);
    }
    char* Example::getName()
    {
    	return str;
    }
    
    int main()
    {
    	Example e("me");
    	e.setName("Aashi");
    	cout<<e.getName();
    	return 0;
    }

  9. #9
    Join Date
    Oct 2010
    Posts
    98

    Re: allocating and deallocating

    here's updated code, it's working but is this the right way?
    please respond..
    Code:
    #include <iostream>
    using namespace std;
    
    class Example
    {
    private:
    	char* str;
    	int len;
    	static int num_strings;
    public:
    	Example(const char* s);
    	Example();
    	~Example();
    	void setName();
    	char* getName();
    	
    };
    int Example::num_strings=0;
    
    Example::Example(const char* s)
    {
    	len=strlen(s);
    	str=new char[len+1];
    	strcpy(str,s);
    	num_strings++;
    }
    Example::Example()
    {
    	len=4;
    	str=new char[4];
    	strcpy(str,"C++");
    	num_strings++;
    }
    Example::~Example()
    {
    	num_strings--;
    	delete[] str;
    }
    void Example::setName()
    {
    	
    	str=new char[2000];
    	cin.getline(str,2000);
    }
    char* Example::getName()
    {
    	return str;
    }
    
    int main()
    {
    	Example e("me");
    	
    	e.setName();
    	cout<<e.getName();
    	return 0;
    }

  10. #10
    Join Date
    Apr 1999
    Posts
    27,449

    Re: allocating and deallocating

    Quote Originally Posted by Aashi View Post
    here's updated code, it's working but is this the right way?
    No it does not work.

    One question -- why are you using char pointers and 'C' functions to do something that can be easily done using std::string?

    First, that code will fail miserably if I just did this:
    Code:
    int main()
    {
    	Example e("me");
            Example e2("you");
            e = e2;
    }
    The reason why it fails is that in the destructor, the same pointer is deleted twice, causing undefined behaviour. You also now have a memory leak.

    Here is another failure:
    Code:
    int main()
    {
    	Example e("me");
            e.setName();
    }
    Now you have a memory leak. The reason is that you did not deallocate the original memory used by the str pointer.

    Bottom line is that if you quit using char pointers and instead used std::string, all of these issues disappear.
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Example
    {
    private:
    	std::string str;
    public:
    	Example(const std::string& s);
    	Example();
    	void setName();
    	std::string getName();	
    };
    
    Example::Example(const std::string& s) : str(s) 
    {}
    
    Example::Example() : str("C++")
    {}
    
    void Example::setName()
    {
        getline(cin, str);	
    }
    
    std::string Example::getName()
    {
    	return str;
    }
    
    int main()
    {
    	Example e("me");
    	e.setName();
    	cout<<e.getName();
    	return 0;
    }
    There is no memory allocation being done, no memory leaks, no undefined behaviour. There is also no need to guess how many characters you need, as the string is dynamically resized.

    If you insist on using char pointers, then you need to learn how to write copy constructor, assignment operator, and know exactly how to manage dynamically allocated memory correctly. But why do that when the code above does everything, easier and safer.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; November 7th, 2011 at 05:21 AM.

  11. #11
    Join Date
    Jun 2008
    Posts
    592

    Re: allocating and deallocating

    Quote Originally Posted by Aashi
    I know, but i want to use this for learning.
    Why not learn from tutorials as well? Also read faqs. They can provide common pitfalls and how to avoid them. Googling your question first is even better if you can generalize it.
    Code:
    void Example::setName() 
    {          
        str=new char[2000];     
        cin.getline(str,2000); 
    }
    What happened to your previous str pointer?
    Is len updated to the new string length?
    How can I set a name without using the console?
    Code:
    char* Example::getName() 
    {     
        return str; 
    }
    What if I have a const Example me and want to call me.getName()?
    0100 0111 0110 1111 0110 0100 0010 0000 0110 1001 0111 0011 0010 0000 0110 0110 0110 1111 0111 0010
    0110 0101 0111 0110 0110 0101 0111 0010 0010 0001 0010 0001 0000 0000 0000 0000
    0000 0000 0000 0000

  12. #12
    Join Date
    Oct 2010
    Posts
    98

    Re: allocating and deallocating

    thanks,

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured