0

In a microcontroller without any OS, how does the microcontroller keep track of where a malloc will point to in the heap?

char *x;
char *y;
char *z;

x=(char*)malloc(10);
y=(char*)malloc(10);
free(x);
z=(char*)malloc(10);

After free(x), are subsequent mallocs able to use the memory that was allocated for x or is it blocked because of malloc for y?

2
  • has nothing to do with microcontrollers. C library items are in the C library (for any target, big or small). Commented Jul 5 at 0:53
  • no guarantee that z will get the space x pointed it, for various reasons starting with implementation. Commented Jul 5 at 0:54

1 Answer 1

1

How does the microcontroller keep track of where a malloc will point to in the heap?

This is implementation defined, malloc will be in some library and compile like any other function. Here is one implementation you can look at: https://github.com/32bitmicro/newlib-nano-1.0/blob/master/newlib/libc/stdlib/malloc.c

Usually, malloc stores a header full of information (like number of bytes allocated) next to each assignment.

After free(x), are subsequent mallocs able to use the memory that was allocated for x or is it blocked because of malloc for y?

free(x) frees up the memory for x, y has nothing to do with it.

For clarity, each call to malloc returns a new pointer. But if x is freed, that memory region could be returned again.

You also don't need to cast the pointer to char*, and it's recommended not to!

Sign up to request clarification or add additional context in comments.

1 Comment

To be nit-picky, malloc itself doesn't "point somewhere in the heap", it returns a pointer to somewhere in the heap!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.