Suppose I have the following piece of code in my program:
char *ptr;
ptr=malloc(sizeof(char)*10);
ptr=malloc(sizeof(char)*10);
ptr=malloc(sizeof(char)*10);
ptr=malloc(sizeof(char)*10);
Will a pointer to the same memory block be assigned to ptr
each time,or a separate piece of memory be reserved each time and its pointer assigned to ptr
,resulting in memory leak each time malloc()
is called?
I am still learning C so bear with me if it's too basic.I tried googling but found no answer.
EDIT::
Thanks for your answers.Please tell me if this approach of me deals with the memory leak risk.My program simply asks for names of 5 people and displays it,without using static arrays.After reading your answers,I put the free(ptr)
inside the loop,else before I had planned to use it only once outside the loop,after the loop.Am I correct now?
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char *names[5],*ptr;
int i;
for(i=0;i<=4;i++)
{
ptr=malloc(sizeof(char)*10);
printf("Enter name no.%d : \n",i+1);
scanf("%s",ptr);
names[i]=malloc(strlen(ptr)+1);
strcpy(names[i],ptr);
free(ptr);
}
for(i=0;i<=4;i++)
printf("%s\n",names[i]);
}