Problems using realloc for decreasing

150 Views Asked by At

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

1

There are 1 best solutions below

0
chqrlie On

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:

#include <stdio.h>
#include <stdlib.h>

void deallocates(int **v, int size) {
    int *newptr;
    int i;

    newptr = realloc(*v, sizeof(int) * size);
    printf("After realloc for size=%d:", size);
    if (newptr == NULL) {
        printf(" reallocation failure\n");
    } else {
        *v = newptr;
        for (i = 0; i < size; i++) {
            printf(" %d", (*v)[i]);
        }
        printf("\n");
    }
}

int main() {
    int i, *v, size, original_size;

    srand(time(NULL));

    printf("size of the vector: ");
    if (scanf("%d", &original_size) != 1)
        return 1;

    v = malloc(sizeof(int) * original_size);
    if (v == NULL)
        return 1;

    printf("Before realloc: ");
    for (i = 0; i < original_size; i++) {
        v[i] = rand() % 100;
        printf(" %d", v[i]);
    }
    printf("\n");

    size = original_size;
    for (i = 1; i < size; i++)
        deallocates(&v, size - i);
    free(v);
    return 0;
}

Output:

size of the vector: 10
Before realloc:  64 90 47 15 62 4 19 67 95 5
After realloc for size=9: 64 90 47 15 62 4 19 67 95
After realloc for size=8: 64 90 47 15 62 4 19 67
After realloc for size=7: 64 90 47 15 62 4 19
After realloc for size=6: 64 90 47 15 62 4
After realloc for size=5: 64 90 47 15 62
After realloc for size=4: 64 90 47 15
After realloc for size=3: 64 90 47
After realloc for size=2: 64 90
After realloc for size=1: 64