As I ask how can I read values from the memory which was put into a memory block by malloc/realloc?
I have a program which creates 2 memory blocks at first and extends until reach 32.Its working fine but in order not to lose values after realloc I start my scanf session with an integer called koru.Koru starts with 0 at the beginning and in every realloc I make its number half of the total amount of memory so I expect not to lose the values entered before realloc sessions but now I need to read what I wrote the memory so I will be sure that I didnt overwrite how can I do that ?
#include "stdio.h"
#include "stdlib.h"
int main()
{
int size=2;
int* p1;
int* p2;
int n;
p1=(int *)malloc((size*sizeof(int)));
int b=0;
int i=0;
int koru=0;
while(size<32)
{
if(i<size){
for(i=koru;i<size;i++)
{
printf("\nEnter value:");
scanf("%d",p1);
}
}
else if(boyut=i)
{
size=size*2;
p2 = (int*) realloc (p1,size*sizeof(int));
p1=p2;
koru=size/2;
printf("\nNOt enough size we make it %d also we protect %d that amount of memory"size,koru);
}
}
return 0;
}
I thought putting a array[i]=p1; and reading it after while loop will solve the problem but later I figured out that its cheating I am not reading from the memory block just reading from another array so this wont work too can somebody lead the way for me please ?
What my program does:
2 blocks memory malloc takes values and fills it When it fills improves the memory size multiplying by 2 realloc starts reading from half number so it dont rewite continues this progress until it reaches 32
Edit:Simplified question:
I put lots of values in the memory after while loop how can I read them ?
I tried to read it like this but all I get is 0
int counter =0;
while (counter<koru)
{
printf("\n%d",p1[counter]);
counter++;
}
return 0;
}
The correct code which creates a memory block with malloc and extends it with realloc after 32 it exits while loop and writes everything from the p1 pointer(from memory) thanks for help.
Working Code below:
#include "stdio.h"
#include "stdlib.h"
int main()
{
int boyut=2;
int* p1;
int* p2;
int n;
p1=(int *)malloc((boyut*sizeof(int)));
int b=0;
int i=0;
int koru=0;
while(boyut<16)
{
if(i<boyut){
for(i=koru;i<boyut;i++){
printf("\nDeğer Girin:");
scanf("%d", &p1[i]);
}
}
else if(boyut=i)
{
boyut=boyut*2;
p2 = (int*) realloc (p1,boyut*sizeof(int));
p1=p2;
koru=boyut/2;
printf("\nBoyut yetersiz yeni boyutu %d yapıyoruz önceki %d kadar alanı korumaya aldık",boyut,koru);
}
}
int counter =0;
while (counter<koru)
{
printf("\n%d",p1[counter]);
counter++;
}
return 0;
}