简体   繁体   中英

C++ pointers to make an array

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...

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM