I am trying to understand the behavior of memory allocation in c. I have written this code: I allocated 1 space of memory of the char pointer, however I am trying to add data to it outside its allocated memory and it is giving me good result. But what is the inconvenience of not allocating the right amount of memory?
int main() {
char *c = (char*)malloc(1*sizeof(char));
c[0]='1';
c[1] ='2';
c[2]='4';
c[3]='3';
c[4]='6';
c[5]='\0';
printf("%s",c);
free(c);
return 0; }
Another question,
for example I have a function that returns a char * and inside this function I am allocating a memory :
char * mallocbyme()
{
char *f = (char*) malloc(4*sizeof(char));
return f;
}
char *d = (char*) malloc(1*sizeof(char));
d= mallocbyme();
My question is what will happen with the first allocated memory assigned to d?
Thank you