使用realloc进行减少的问题

时间:2019-03-31 15:52:47

标签: c realloc memory-reallocation

我正在尝试使用realloc进行删除,但是它没有按我期望的方式工作...

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);
}

有时候我想删除的值仍然存在。请在我的代码输出中看到这张照片。我在烦人的线条上画了一个红色的标记: https://ibb.co/C1TMHF5

1 个答案:

答案 0 :(得分:0)

您的代码具有未定义的行为,因为您访问的内存超出了分配的块的末尾。您无法安全地检查超出重新分配对象的新大小的字节。

这是修改后的版本:

#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;
}

输出:

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