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
CodePudding user response:
It is undefined behaviour to write outside the memory given to you by malloc
, calloc
, etc. The 'inconvenience' is that your program may or may not work each time you run it, as the operating system won't always check if you are reading/writing inside of the bounds of your memory chunk. In reality what probably happened is that the OS allocated you more memory than you asked so you have a bit of leeway before you get a segfault. But by no means does this mean that you should write out of the bounds of what you allocated.
In your second block of code, because you assigned to d
the return value of mallocbyme
without freeing the original malloc, you now have a memory leak.
CodePudding user response:
am trying to understand the behavior of memory allocation in c.
I am trying to add data to it outside its allocated memory
This is undefined behavior (UB). Anything may happen. To understand the behavior of memory allocation in C, use code with defined behavior.
Start with
// char *c = (char*)malloc(1*sizeof(char));
char *c = malloc(sizeof c[0] * 6);
if (c) {
...