Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc in for loop

i have a question... lets say i have the following part of code :

int *a,*a1,*a2;
for (i=1; i<=2; i++) {
    a=malloc(sizeof(int));
    if (i==1) a1=a;
    else if (i==2) a2=a;
}
*a1=5;
*a2=4;

so my question is if i use printf to print a1 and a2 the variable a1 is gonna to have the value 5 and the a2 the value 4 ? so if i use malloc to allocate memory and a points in that memory space and use again malloc to allocate memory then a points to a different part of memory but the first one part of memory still exist ? or if i use malloc with a again it will erase the first part of memory and it will write a new part of memory

like image 219
user1809300 Avatar asked Jan 31 '26 18:01

user1809300


1 Answers

Each call to malloc returns a pointer to different memory, until you call free to release that memory.

like image 62
Eric Postpischil Avatar answered Feb 02 '26 09:02

Eric Postpischil