I am trying to delete with realloc but it isn't working the way I expected...
void deallocates(int** v, int size, int original_size) {
int i;
*v = (int*)realloc(*v, sizeof(int) * size);
printf("\nAFTER REALLOC FOR SIZE = %d\n", size);
for (i = 0; i < original_size; i++) {
printf("%d ", (*v)[i]);
}
}
int main() {
int i, *v, size, original_size;
srand(time(NULL));
printf("size of the vector: ");
scanf("%d", &original_size);
v = (int *)malloc(sizeof(int) * original_size);
printf("before realloc...\n");
for (i = 0; i < original_size; i++) {
v[i] = rand() % 100;
printf("%d ", v[i]);
}
size = original_size;
for (i = 1; i < size; i++)
deallocates(&v, size - i, original_size);
}
The values that I wanted to be deleted sometimes remains. Please see this photo with the output of my code. I painted a red mark at the lines that are annoying me: https://ibb.co/C1TMHF5
Your code has undefined behavior because you access memory beyond the end of the allocated block. You cannot safely examine the bytes beyond the new size of the reallocated object.
Here is a modified version:
Output: