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...
delete(str)will free the memory allocated at the original address. Addingicauses the pointer to be invalid.stris too. What exactly isnew charputting 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 onecharthere, in which case, where are the rest of teh characters going???