I noticed in line 168 and 169 there're delete [] hold_value; delete [] chosen;
But these two lines appear again in line 409 and 410, do these have any side effects? Or actually only needs once?
Also, in first_2_opt function, since it is a void function, do we still need line 333 (delete [] x?
pointer = nullptr; Is this also considered an initialisation of the pointer? To an empty address.
> I noticed in line 168 and 169 there're delete [] hold_value; delete [] chosen;
Having the same name for a local variable in two different functions doesn't make it the same variable. Each instance has it's own separate existence, and operations on one have nothing to do with operations on the other.
The ones in main are never used for anything to begin with, and could be safely removed from the code, along with a few other variables in main which serve only to clutter.
> Also, in first_2_opt function, since it is a void function, do we still need line 333 (delete [] x?
...
> x = generate_random_vector(n);
This generates a new[] vector and returns it to first_2_opt_symmetric.
You have exactly 3 options:
- you delete[] it when you're done.
- you return x to the caller function for them to take responsibility for deleting.
- you save x somewhere safe so you can delete it later on - say when the program ends.
If you just let the function exit without doing one of those things, then you have a memory leak.
Every 'new' needs a 'delete' and every 'new[]' needs a 'delete[]'.
So every time you call either new, you need to be thinking at the same time, "OK, where does the corresponding delete go in this code?". Your code wouldn't work if you neglected putting all the { } in the right places.
> pointer = nullptr; Is this also considered an initialisation of the pointer? To an empty address.
Yes.
> Is pointer = nullptr more preferable than *pointer = new []? Or they have different functions?
1 2 3
int *ptr;
...
ptr[0] = 0;
This is an uninitialised pointer, and its a crap-shoot as to what happens when you try to dereference the pointer.
1 2 3
int *ptr = nullptr;
...
ptr[0] = 0;
This is an initialised null pointer, and it's pretty much guaranteed on any sane machine that it will segfault when you try to dereference the pointer. Doing this is far more preferable than the randomised chaos of using an uninitialised pointer by mistake.
1 2 3
int *ptr = newint[1];
...
ptr[0] = 0;
You can assign and use ptr[0] all you want until the cows come home.
How do I do that? Since I'm using Dev C++, so it comes with the old compiler. Any suggestions for other IDE's'? I tried Visual Studio but errors keep occurring in my code.
Sorry for being so careless, I thought that line was extra so I commented out and I forgot I did that. Really sorry for causing you unnecessary trouble. The code works fine now, I'm sorry again and thanks.