-1

I hope you're all having a good day! So I want to create a class which saves a word (string) as a character array. I allocated memory to str in the default constructor, not sure if that's how it works.

`   #include <iostream>
    using namespace std;
    class String{
      private:
      char *str;
      public:
      String(){
        str=new char[10];
        str="Hello";
      }
      void getstr(){
        for (int i=0;i<5;i++){
          cout<<str[i];
        }
      }
      ~String(){
        delete []str;
      }
    };
    int main(){
      String s1;
      s1.getstr();
      return 0;
    }

When i run this program, it does print "Hello" but this is the exact output:

*** Error in `./main': free(): invalid pointer: 0x0000000000400ab5 ***
Hello

When i removed the destructor part, it worked fine,but i need to free the memory allocated to str,right? Any help?

Thanks in advance :)

Zarish
  • 205
  • 1
  • 2
  • 5
  • 2
    Perhaps use `std::string`? Also this `str="Hello";` does not make sense – Ed Heal Mar 19 '17 at 18:12
  • 4
    `char str[100];` is followed by `str=new char[10];`, and then, surprisingly enough, by `str="Hello";`. What's going on here? – ForceBru Mar 19 '17 at 18:13
  • Possible duplicate of [How to free an array in C/C++](http://stackoverflow.com/questions/33335668/how-to-free-an-array-in-c-c) – domsson Mar 19 '17 at 18:13
  • @ForceBru i accidently wrote `str[100]` in the question, it was actually `*str` when i compiled it. – Zarish Mar 19 '17 at 18:17

1 Answers1

3
    str=new char[10];
    str="Hello";

The first line allocates a new char array which can hold 10 chars (or 9 chars and a null byte). The second line however, sets the pointer str to the address of your string literal "Hello". Thus, when you call delete [], you are trying to free a pointer to string literal and not a pointer to some dynamically allocated memory. If you want your string to be dynamically allocated, you should copy your string (preferably using strcpy), or just use std::string, which will take care of memory management for you.

Ben Steffan
  • 1,095
  • 12
  • 16
  • I want to do it without using 'string'. Is there a way i can do that? – Zarish Mar 19 '17 at 18:26
  • @Zarish the answer is right there: "you should copy your string (preferably using strcpy)" – anatolyg Mar 19 '17 at 18:31
  • @Zarish - And after fixing the constructor, you should also look into adding a copy constructor and an assignment operator. Otherwise you will soon get "double delete" errors. (Or just use a `std::string` which takes care of everything :-). – Bo Persson Mar 19 '17 at 18:44
  • Also, if you are using C++… then why don't want to use string? There is nothing wrong or slow in it. – rlam12 Mar 19 '17 at 18:50