1

This program crashes and I can't find any nonlegal action regarding getting array content and moving pointer. What is wrong?

#include <iostream>
#include <stdint.h>
using namespace std;


int main( int argc, char ** argv ) {


    int * p =  new int [20];
    for(int i=0 ; i<20 ;i++ )
        {
            p[i]=i;
        }

    for(int i=0 ; i<20 ;i++ )
        {
            printf("%d ",*p );
            p++;
        }


    delete [] p;

    return 0;
}
2
  • 1
    Question: Why are you using new in the first place? You're going through a lot of extra gyration to get pretty much the result you'd get from just making p an array/std::vector/std::array local to main. You've gotten lots of advice about how to keep the new/delete from crashing, but none that points out that you shouldn't be using them to start with (and even when you need new-like capabilities, you should look at make_shared and make_unique instead of using new directly). Commented Nov 25, 2013 at 17:03
  • @JerryCoffin let me answer that - mostly because majority of C++ books, resources, courses (even the University ones) still prefer to show how to implement linked list in C and then to compile it with C++ compiler. People are still teaching other people how to feel comfortable inside "C ghetto" (as Bartosz Milewski named it). Commented Nov 25, 2013 at 17:12

3 Answers 3

6

You're changing your p pointer, and then you're trying to delete memory after the original allocated memory:

delete [] p;

Save the the original pointer to some temporary iterator pointer and increment it, and not the original one:

    int *t = p;
    for(int i=0 ; i<20 ;i++ )
    {
        printf("%d ",*t );
        t++;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

You are deleting a pointer pointing to the next element after your memory block.

Comments

2

Save starting pointer of array in another pointer and delete that old pointer on the end.

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.