0

I am new to C++ ... I am playing with pointers ... This code uses a char ptr as an array .

#‎include‬<iostream>
using namespace std;

int main (){

    cout << "Playground "<<endl;

    const short max=10;

    char * str=new char ;

    for (short i=0;i<max;i++)
        *(str+i)=char(i+100);

    for (short i=0;i<max;i++)
        cout <<str+i<< char(3) <<endl;

    for(short i=0;i<max;i++)
        delete (str+i);

    return 0;
}

But I am not sure if delete (str+i) works or not , and why ? But I think it does not work because I have run the program many times and although the string is printed :

Playground
defghijklm
efghijklm
fghijklm
ghijklm
hijklm
ijklm
jklm
klm
lm
m

I have this error message

try #0
*** Error in `./p': free(): invalid pointer: 0x09d90009 ***
Aborted (core dumped)

try #1
*** Error in `./p': free(): invalid pointer: 0x08453009 ***
Aborted (core dumped)

try #2
*** Error in `./p': free(): invalid pointer: 0x0863c009 ***
Aborted (core dumped)

etc ...

Because the invalid pointer keep changing , I have the feeling that the objects has not been deleted or garbage collected and every time I run the code I use another area of the memory ...

Finally I am starting to get why regular array are better ...

*from the beginning a contiguous space in memory is reserved for the data

*not need to worry about delete ...

Those are just my guesses...

2
  • delete(str) will free the memory allocated at the original address. Adding i causes the pointer to be invalid. Commented Jan 16, 2015 at 9:27
  • You probably want to look at how big the 'string' at str is too. What exactly is new char putting there? Is it a big enough string? If so, how does the compiler know how big it has to be? Maybe it is only placing one char there, in which case, where are the rest of teh characters going??? Commented Jan 16, 2015 at 9:30

2 Answers 2

3

You have out of bound access:

char* str = new char; // single element

should be

char* str=new char[max]; // array of char

and you have to release memory with

delete [] str;

but to avoid to manage memory manually, you may use std::string or std::vector<char>

Sign up to request clarification or add additional context in comments.

Comments

1

You are only making one dynamic memory allocation, and for just 1 char, but you are deleting dynamically allocated memory multiple times in the last for-loop - you can only do one delete for every new.

Additionally, in the first for-loop you assign new char values to memory outside of what you allocated, which means you are overwriting memory that isn't yours.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.