Crealloc() question.

Asked 2 years ago, Updated 2 years ago, 29 views

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include <time.h>

int main()
{
    unsigned char *test;
    int i;
    test = (unsigned char*)malloc(5);

    for(i = 0; i < 5; i++)
    {
        test[i] = 0x11;
    }
     for(i = 0; i < 5; i++)
    {
        printf("%d. 0x%x\n ", i, test[i]);
    }

    printf("\n");


    test = (unsigned char*)realloc(test,3);

     for(i = 3; i < 5; i++)
    {
        test[i] =0xff;

    }

    for(i = 0; i < 5; i++)
    {
        printf("%d. 0x%x \n", i, test[i]);
    }

    free(test);

    return 0;
}

At first, I was assigned 5 by malloc() and then reduced to 3 by realloc(), but I want to know why it approaches test[4]. Shouldn't we print out the value up to test[2] and then get a garbage value or other value instead of 0xff?

c realloc

2022-09-22 11:53

1 Answers

The value in memory that is used by other programs and not cleaned up is trash value

The test[4] is also trash It hasn't been long since you initialized it, so the last value you put in is maintained, so you don't know when and who will use it and change it.


2022-09-22 11:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.