Malloc -> how much memory has been allocated?

后端 未结 7 1278
梦谈多话
梦谈多话 2020-12-20 18:44
# include 
# include 
# include 
# include 

int main ()
{
  char * buffer;
  buffer = malloc (2);

          


        
7条回答
  •  萌比男神i
    2020-12-20 19:05

    Why doesnt the compiler give me an error telling me there isnt enough memory allocated ?

    C does not block you from using memory you should not. You can use that memory, but it is bad and result in Undefined Behaviour. You are writing in a place you should not. This program might appear as running correctly, but might later crash. This is UB. you do not know what might happen.

    This is what is happening with your strcpy(). You write in place you do not own, but the language does not protect you from that. So you should make sure you always know what and where you are writing, or make sure you stop when you are about to exceed valid memory bounds.

    I read a couple of questions that ask how to check how much memory malloc actually allocates but I didn't find a concrete answer. Shouldn't the 'free' function have to know how much memory is exactly allocated to 'buffer' ?

    malloc() might allocate more memory than you request cause of bit padding.

    More : http://en.wikipedia.org/wiki/Data_structure_alignment

    free() free-s the exact same amount you allocated with malloc(), but it is not as smart as you think. Eg:

    int main()
    {
         char * ptr = malloc(10);
         if(ptr)
         {
             ++ptr; // Now on ptr+1
             free(ptr); // Undefined Behaviour
         }
    }
    

    You should always free() a pointer which points to the first block. Doing a free(0) is safe.

提交回复
热议问题