realloc () function

Prototype: extern  void * realloc ( void * mem_address, unsigned int newsize); 
Parameters: mem_address: To change the name of the pointer memory size 
        newsize: the new memory size.

If you reduce the allocated memory, realloc only change the index information.

If the allocated memory to expand, there are about several situations:

1) If necessary after the current memory segment of memory space, this memory space directly expanded, realloc () returns a pointer element.

2) If the current memory segment back idle bytes is not enough, then a first experiment to meet this requirement heap memory block copy current data to a new location, and the original data block freed, returns a new block of memory locations.

3) If the application fails, it returns NULL, this time, the original pointer is still valid.

 

Note: If the call succeeds, regardless of the back of the current memory segment free space meets the requirements, will relieve the original pointer, return to a pointer, although the pointer returned is possible and the original pointer, like, that can not be released again off the original pointer

/***
realloc.c
***/
#include<stdio.h>
#include<stdlib.h>

int main(int argc,char ** argv)
{
    int input;
    int n;
    int *numbers1;
    int *numbers2;
    numbers1 = NULL;

    if( (numbers2 = (int*)malloc(5*sizeof(int))) == NULL)
    {
        printf("malloc memory unsuccessful");
        exit(1);
    }

    printf("numbers addr:%8X\n",(int)numbers2);

    for(n = 0; n < 5; n++)
    {
        *(numbers2+n) = n;
        printf("numbers2's data %d\n",*(numbers2+n));
    }

    printf("Enter new size: ");
    scanf("%d",&input);

    numbers1 = (int *)realloc(numbers2,(input+5)*sizeof(int));

    if(NULL == numbers1)
    {
        printf("Error (re)allocating memory");
        exit(1);
    }

    printf("numbers1 addr: %8X\n",(int)numbers1);

    for(n = 0; n < input; n++)
    {
        *(numbers1+5+n) = n + 5;
    }

    printf("\n");

    free(numbers1);
    numbers1 = NULL;
    
    return 0;
}

If the current memory segment have enough space, realloc () returns a pointer to the original:

ubuntu14-04@ubuntu:~/ShareWin/shiyanlou/C/file$ ./realloc
numbers addr:  D07010
numbers2's data 0
numbers2's data 1
numbers2's data 2
numbers2's data 3
numbers2's data 4
Enter new size: 10
numbers1 addr:   D07010

Current memory segment is not enough space, realloc () returns a pointer to the new memory segment:

ubuntu14-04@ubuntu:~/ShareWin/shiyanlou/C/file$ ./realloc
numbers addr: 25E8010
numbers2's data 0
numbers2's data 1
numbers2's data 2
numbers2's data 3
numbers2's data 4
Enter new size: 10000
numbers1 addr:  25E8010

 

Guess you like

Origin www.cnblogs.com/wanghao-boke/p/11606187.html