I am now entering the part of memory management.
As learning from some resources, realloc copies the content pointed by a declared pointer, frees its memory and then allocates a new memory space as well as pasting its previous value.
The first sample code uses only realloc to dynamically increase the size and input some value.
It works well.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i = 0, n = 0, x = 0, *p = NULL;
while(scanf("%d", &x) != EOF){
++n;
p = (int *)realloc(p, n * sizeof(int));
p[n-1] = x;
for(i=0; i<n; ++i)
printf("%d, ", p[i]);
printf("\n");
}
free(p);
system("pause");
return 0;
}
In the second code, I tried to allocate the memory space and give value by malloc.
Then I tried to use realloc to change the size of memory space but keep the previous value.
However, it fails.
Where did I do wrong?
Thanks!!
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void){
int n;
char* pc = NULL;
int i;
scanf("%u",&n);
pc = (char*)malloc(sizeof(char)*n); // borrow memory spaces using malloc
for(i=0;i<n;i++) pc[i]=(char)i*(char)i;
for(i=0;i<n;i++) printf("%d ",pc+i);
printf("\n");
for(i=0;i<n;i++) printf("%d ",*(pc++));
printf("\n");
//free(pc);
n=n+3;
pc = (char*)realloc(pc,sizeof(char)*n); // try to change the memory size but keep the values using realloc
for(i=0;i<n;i++) printf("%d ",pc+i);
printf("\n");
for(i=0;i<n;i++) printf("%d ",*(pc++));
printf("\n");
free(pc);
system("pause");
return 0;
}