resizing dinamic array

hi
i saw this topic(http://www.cplusplus.com/forum/general/11111/)(I can't respond)

i do the thing of malloc and realloc

but if i did

1
2
3
4
5
6
7
int * arr = (int*) malloc(3);
arr[0] = 2;
arr[1] = 4;
arr[2] = 6;
arr = (int *) realloc(arr,4);
arr[3] = 7;
arr = (int *) realloc(arr,3);


the array have the size of 3, but the 4 position, remain in memory
exist something to delete the 4 position?

thanks for you time.


Last edited on
int * arr = (int*) malloc(3);

This is wrong. It should be: int * arr = (int*)malloc(3 * sizeof(int));

A common mistake... which is one of the reasons why you shouldn't use malloc in C++.

Likewise, your reallocs have the same problem.

Consider using a vector instead.

the array have the size of 3, but the 4 position, remain in memory
exist something to delete the 4 position?


After you realloc to reduce the buffer, the [3] position no longer exists (for your purposes). Whether or not it gets wiped/cleaned does not matter. For all you care, it is no longer accessible.
After you realloc to reduce the buffer, the [3] position no longer exists (for your purposes). Whether or not it gets wiped/cleaned does not matter. For all you care, it is no longer accessible.


i try this
1
2
3
4
5
6
7
8
9
10
 
     int * arr = (int*) malloc(3* sizeof ( int ));
     arr[0] = 2;
     arr[1] = 4;
     arr[2] = 6;
     arr = (int *) realloc(arr,4* sizeof ( int ));
     arr[3] = 8;
     arr = (int *) realloc(arr,3* sizeof ( int ));
     cout << arr[3];
     return 0;


but print 8

maybe i will use a vector

thanks anyways
Last edited on
Out of bounds causes undefined behaviour.
i try this
...
but print 8


That doesn't matter. You're accessing memory that is no longer allocated. It doesn't matter what is stored in that memory anymore.

As ne555 said, it's undefined behavior. It might be 8, it might be -12387429.


That doesn't matter. You're accessing memory that is no longer allocated. It doesn't matter what is stored in that memory anymore.

As ne555 said, it's undefined behavior. It might be 8, it might be -12387429.


understand, imma little slow hehe, that part is not finally convinced me, but now I do.

thanks to all
Topic archived. No new replies allowed.