Malloc & # 8594; how much memory was allocated?

# include <stdio.h> # include <stdbool.h> # include <string.h> # include <stdlib.h> int main () { char * buffer; buffer = malloc (2); if (buffer == NULL){ printf("big errors"); } strcpy(buffer, "hello"); printf("buffer is %s\n", buffer); free(buffer); return 0; } 

I allocated 2 bytes of memory to the / char pointer buffer, but if I assign it β€œhi”, it will still print it without giving me any errors. Why doesn't the compiler give me an error saying that the allocated memory is not enough? I read a couple of questions that ask how to check how much malloc memory is actually allocated, but I did not find a specific answer. Should the free function know exactly how much memory is allocated for buffer ?

+7
source share
7 answers

The compiler does not know. This joy and horror of C. malloc belongs to runtime. All compilers know that you said that it returns void *, it does not know how much or how much strcpy is going to copy.

Tools like valgrind detect some of these errors. Other programming languages ​​make it difficult to shoot in the leg. Not C.

+14
source

No malloc() implementation should prevent you from trying to write the past that you highlighted. It is assumed that if you allocate 123 bytes, you will use all or less of what you allocated. malloc() , for efficiency, should assume that the programmer will keep track of their pointers.

Using memory that you haven't explicitly set and asked malloc() to give you undefined behavior. You may have requested n bytes, but received n + x, due to optimizing the implementation of malloc() to align the bytes. Or you can write in a black hole. You can never know why this behavior is undefined.

It is said ...

There are versions of malloc() that give you built - in statistics and debugging , however they should be used instead of the standard malloc() , as if you were using a garbage collector .

I also saw options specifically designed for LD_PRELOAD that expose a function that allows you to define a callback with at least one void pointer as an argument. This argument assumes a structure containing statistics. Other tools, such as an electric fence , will simply stop your program from giving exact instructions that lead to overflow or access to invalid blocks. As @R .. notes in the comments, this is great for debugging, but terribly inefficient.

It’s fair for everyone or (as they say) β€œat the end of the day” - it’s much easier to use a heap profiler, for example Valgrind and related tools ( massif ) in this case, which will give you quite a lot of information. In this particular case, Valgrind would point out the obvious - you wrote the previously highlighted border. In most cases, however, when this is not intentional, a good profiler / error detector is priceless.

Using a profiler is not always possible because of:

  • Problems with synchronization while working under the profiler (but they are common when all calls to malloc() intercepted).
  • Profiler is not available for your platform / arch
  • Debugging data (from the malloc() log) should be an integral part of the program

We used the library option that I linked in HelenOS (I'm not sure they still use it) for quite some time, since, as you know, debugging in VMM is crazy.

However, think about future consequences when considering replacing, when it comes to the malloc() object, you almost always want to use what the system sends.

+4
source

How much malloc internally allocates depends on the implementation and depends on the OS (for example, multiples of 8 bytes or more). Your write to unallocated bytes can overwrite other variable values, even if your compiler and runtime do not detect an error. A free function remembers the number of bytes allocated separately from the selected area, for example, in a free list.

+1
source

Why doesn't the compiler give me an error telling me that this is insufficiently allocated memory?

C does not block the use of memory, which you should not. You can use this memory, but it is bad and leads to Undefined Behavior. You write in a place where you should not. This program may appear to work correctly, but may crash later. This is UB . you do not know what might happen.

This is what happens to your strcpy() . You write that you do not speak, but the language does not protect you from this. Therefore, you must be sure that you always know what and where to write, or make sure that you stop when you are going to exceed the permissible memory limits.

I read a couple of questions that ask how to check how much memory malloc actually allocates, but I did not find a specific answer. Should not be "free" function should know how much memory is allocated "buffer" exactly?

malloc() may allocate more memory than you ask for a reason for the bits to be full.

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

free() free the same amount that you allocated with malloc() , but it is not as smart as you think. For example:

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

You should always have a free() pointer pointing to the first block. Running free(0) safe.

+1
source

You wrote for the end of the buffer you allocated. The result is undefined behavior. Some run-time libraries with the correct parameters have at least some ability to diagnose such problems, but not all of them do, and even those that do this only at runtime, and usually only when compiling with the correct parameters.

+1
source

Malloc β†’ how much memory has been allocated?

When you allocate memory using malloc. If successful, it allocates memory, and the default distribution is 128k. The first malloc call gives you 128k.

what you requested is buffer = malloc (2); Although you requested 2 bytes. He allocated 128k.

strcpy(buffer, "hello"); A dedicated 128k chunk started processing your request. The "hello" string may fit into this.

This pgm will cleanse you.

 int main() { int *p= (int *) malloc(2);---> request is only 2bytes p[0]=100; p[1]=200; p[2]=300; p[3]=400; p[4]=500; int i=0; 

for (; i <5; i ++, p ++) enter code here E ("% d \ t", * p);

 } 

On the first call to malloc. It allocates 128k ---> from what is processing your request (2 bytes). The string "hello" may fit into it. Again, when the second call to malloc processes your request from 128k.

In addition to 128k, it uses the mmap interface. You can go to the malloc man page.

0
source

There is no compiler / platform independent way to find out how much malloc memory is actually allocated. malloc will be in the overall distribution a little more than you ask for it here:

http://41j.com/blog/2011/09/finding-out-how-much-memory-was-allocated/

On Linux, you can use malloc_usable_size to find out how much memory you can use. On MacOS and other BSD platforms, you can use malloc_size. The post linked above contains complete examples of both of these methods.

0
source

All Articles