Malloc replacement by user - c++

I want to ask you for help with my own project.
I want to try to replace original malloc, free functions by my own functions which will have same behavior.
int memory_free(void *ptr){}
void memory_init(void *ptr, unsigned int size){}
void *memory_alloc(unsigned int size){}
The memory_init function will create a memory to work with. At the beggining there will be pointer for example *Memory and it will be the argument for memory_init. Memory init will be called only once at the beginning of the program.
#include <string.h>
int main()
{
char region[50];
memory_init(region, 50);
char* pointer = (char*) memory_alloc(10);
if (pointer)
memset(pointer, 0, 10);
if (pointer)
memory_free(pointer);
return 0;
}
this code is the example of testing my functions. Memory_init will initialize memory and memory_alloc will create blocks in this memory for every call.
If there is someone who have idea how to make it i will be glad to see your answer.
Sorry for my english.
thx.
for memory_init i have this
*Memory;
void memory_init(void *ptr, unsigned int size){
*((unsigned int*)ptr)=size; //at first position there will be size of whole memory;
}
My idea is to make one block of memory and in it there will be small block. every block will have head. at first position there will be size of block and after it there will be tag if it is free or not and after it there will be end of the block.

Section 8.7 of the classic Kernighan&Ritchie "The C Programming Language" describes exactly what you are asking in simple terms. You can find copies of it on the web in various places. You can also find more sophisticated malloc implementations here or here

malloc() uses the sbrk system call to request more memory. Afaik it is the only way to do it.

Related

_alloca and std::vector of const char*

I did several searches on the _alloca function and it is generally not recommended.
I will have a dynamically updated array of strings on which I will have to iterate often.
I would like to have each string allocated on the stack to reduce the miss caches as much as possible.
Using _alloca I could create a char* on the stack and put it in the vector.
My char will be in a vector which will not impact my stack and I know that the strings will never be big enough to make a stackoverflow when I allocate them on the stack.
Is it a bad thing to use it in this case?
Does the program do what I want it to do?
#include <vector>
#include <cstring>
#ifdef __GNUC__
# define _alloca(size) __builtin_alloca (size)
#endif /* GCC. */
std::vector<const char*> vec;
void add(const char* message, int size) {
char* c = (char*) _alloca (size * sizeof(char*));
std::memcpy(c, message, sizeof(message));
vec.push_back(c);
}
int main() {
const char* c = "OK";
for (int i = 0; i < 10; ++i) {
add(c, 2);
}
}
Stack memory allocated by _alloca gets automatically released when the function that calls _alloca returns. The fact that a pointer to it gets shoved someplace (specifically some vector) does not prevent this memory from being released (as you mentioned you assumed would happen, in the comments), that's not how C++ works. There is no "garbage collection" in C++.
Therefore, the shown code ends up storing a pointer to released stack memory. Once add() returns, this leaves a dangling pointer behind, and any subsequent use of it results in undefined behavior.
In other words: yes, it's "a bad thing to use it in this case", because be the shown code will not work.
There are also several other, major, issues with this specific _alloca call, but that's going to be besides the point. This entire approach fails, even if these issues get fixed correctly.

How to remove all but the vector function of ArduinoSTL

Issue
I did a C++ program running on an Arduino UNO.
I'm using ArduinoSTL only for his vector functionality, but it is using 459 bytes of the Arduino's RAM (23% of wasted RAM is way too much for what I do), and it takes 5 seconds more to compile with this library (which is annoying).
What I want to do
I want to be able to do change the size of arrays, maybe with vectors.
I don't want to use libraries that wastes RAM for nothing.
What I've though of doing
I though that, maybe I could remove everything but the vector function(s) of ArduinoSTL, so it will compile faster and take less RAM.
I attempted to do it.
In ArduinoSTL's directory, there is a lot of .cpp files with one of them named Vector.cpp.
My solution was to erase everything except Vector.cpp.
It didn't worked.
Solution 1
Use regular arrays!
Using a big regular array can be better sometime because ArduinoSTL takes a lot of memory and removing lets enough free space to use such simple arrays and the compiling is way faster.
In what I was doing, I didn't really needed a vector. A big array was enough.
Solution 2
Use stdlib.h!
It provides some functions such as malloc(), calloc(), realloc() and free().
The main advantage is that it is standard and is not only for Arduino.
Here is a piece of code in a regular C++ coding to show how to use it.
#include <stdlib.h> //Mandatory for memory manipulation
#include <stdio.h> //Used to for the command prompt
int main(){
uint8_t* MemBlock=nullptr; //Just a pointer pointing to nothing
int BlockSize=0; //The size of the block in bytes
bool Condition=true; //The condition for the if() statement
if(Condition){
BlockSize=64;
MemBlock=(uint8_t)malloc(BlockSize); //Allocates a Memory Block
uint8_t* P=MemBlock; //Defines a pointer that points to same location as the MemBlock pointer
for(int i=0;i<BlockSize;i++){
*P=i*23%101; //Change the pointed value by P
P++; //Moves to the next value (of MemBlock)
}
}else{
BlockSize=256;
MemBlock=(uint8_t)malloc(BlockSize); //Allocates a Memory Block
for(int i=0;i<BlockSize;i++){
MemBlock[i]=i*17%23; //Fills the Memory Block with values
}
}
uint8_t* P=MemBlock; //Defines a pointer that points to same location as the MemBlock pointer
for(int i=0;i<BlockSize;i++){
std::cout<<*P++<<' '; //Displays all values of the Memory Block, *P++ is same as doing *P then P++
}
std::cout<<'\n'; //ends the line to show it
free(MemBlock); //Deallocates the Memory Block to prevent "memory leaks"
return 0;
}
The Arduino IDE doesn't require to include the library as it is already included by default.
Here is a link for more details about the library: stdlib.h - C++ reference
If anyone know a fast vector library, then feel free to share!

Determine the nature of parameter in runtime

I have a function
void fname(char* Ptr)
{
...
}
I want to know inside this function whether this pointer Ptr holds the address of dynamically allocated memory using new char[] or the address of locally allocated memory in the calling function. Is there any way I can determine that? I think <typeinfo> doesn't help here.
One way to do this is to have your own operator new functions and keep track of everything allocated so that you can just ask your allocation library if the address given is one it allocated. The custom allocator then just calls the standard one to actually do the allocation.
Another approach (messy and details highly OS dependent) may be to examine the process layout in virtual memory and hence determine which addresses refer to which areas of memory.
You can combine these ideas by actually managing your own memory pools. So if you get a single large chunk of system memory with known address bounds and use that for all new'd memory, you can just check that an address in is the given range to answer your question.
However: Any of these ideas is a lot of work and not appropriate if this problem is the only purpose in doing so.
Having said all that, if you do want to implement something, you will need to work carefully through all the ways that an address might be generated.
For example (and surely I've missed some):
Stack
Return from new
Inside something returned from new.
Was returned from new but already deleted (hopefully not, but that's why we need diagnostics)
statically allocated
static constant memory
command line arguments/ environment
code addresses.
Now, ignoring all that for a moment, and assuming this is for some debug purpose rather than system design, you might be able to try this kind of thing:
This is ugly, unreliable, not guaranteed by the standard, etc etc, but might work . . .
char* firstStack = 0;
bool isOnStack(const void* p)
{
char* check =(char*)p;
char * here = (char*)&check;
int a = firstStack - check;
int b = check - here;
return (a*b > 0);
}
void g(const char* p)
{
bool onStack = isOnStack(p);
std::cout << p << (onStack ? "" : " not" ) << " on stack " << std::endl;
}
void f()
{
char stuff[1024] = "Hello";
g(stuff);
}
void h()
{
char* nonsense = new char[1024];
strcpy(nonsense, "World");
g(nonsense);
delete [] nonsense;
}
int main()
{
int var = 0;
firstStack = (char*)&var;
f();
h();
}
Output:
Hello on stack
World not on stack
The short answer: no, you can't. You have no way of knowing whether Ptr is a pointer to a single char, the start of a statically allocated array, a pointer to a single dynamically allocated char, or the start of an array thereof.
If you really wanted to, you try an overload like so:
template <std::size_t N>
void fname(char Ptr[N])
{
// ...
}
which would match when passed a statically allocated array, whereas the first version would be picked when dealing with dynamically allocated memory or a pointer to a single char.
(But note that function overloading rules are a bit complicated in the presence of templates -- in particular, a non-template function is preferred if it matches. So you might need to make the original function take a "dummy" template parameter if you go for this approach.)
In vc++ there is an assertion _CrtIsMemoryBlock (http://msdn.microsoft.com/en-us/library/ww5t02fa.aspx#BKMK_CRT_assertions) that can be used to check if a pointer was allocated from the heap. This will only work when a debug heap is being used but this is fine if you are just wanting to add some 'debug only' assertions. This method has worked well for me in the past under Windows.
For Linux however I know of no such equivalent.
Alternatively you could use an inline assembler block to try to determine the if it is a stack address or not. This would be hardware dependent as it would rely heavily not only on the processor type but also on the memory model being used (flat address model vs segmented etc). Its probably best to avoid this type of approach.

Memory allocation for incremental garbage collection simulation in c++

I need to simulate an incremental garbage collection algorithm in C++ or Java. I had a doubt based on this.
As an input (stdin from keyboard), I will be asked to allocate some memory for this code. The syntax would be:
x = alloc(128KB);
My question: is it ok to use malloc for the assignment? Or is there any other way to allocate memory? I had this doubt because, the size can go up to GB for the assignment, so using malloc might not be a good idea I think.
First of all, if you want to prohibit a huge memory allocation, just check users' input value, but I'm not sure how much memory you think as a huge memory. I think you don't worry about that, because if memory allocation failed, malloc and calloc will return a NULL pointer.
Secondly, you can also use 'calloc' for this case.
void calloc(size_t num, size_t size);
'num' is mean elements' count for allocation and 'size' is, of course, the size of element. Below codes have the same result.
ar = (int *)malloc(5 * sizeof(int));
ar = (int *)calloc(5, sizeof(int));
However, if you choose 'calloc', you may manage more logically your code, since you can divide memory quantity by unit and count.
Also, if you use 'calloc', you don't need to use memset for setting memory value to zero.
'calloc' set automatically memory value to zero.
I hope this article can help you.
malloc can allocate as much memory as you wish provided you don't go past ulimits. Give the following a go to test it out:
#include <stdlib.h>
#include <string.h>
#define ONEGB (size_t)(1073741824)
int main() {
char *p;
p = malloc(ONEGB);
if (!p) {
perror("malloc");
}
else {
memset(p, 0, ONEGB);
}
return 0;
}

C++ memory pool with char array

I just have a quick question regarding how a char array works in regards to a memory pool and allocating pointers of other variable types to it. I am working on an assignment which uses a char array for a memory pool and I need to be able to allocate pointers to it, and I have read some info on the subject but am not quite understanding one part which is how the actual allocation works such as:
const int poolSize = 60000;
char pool[poolSize];
void* allocate(int aSize)
{
//.....
return ((void*) 0);
}
long* pointer;
pointer = (long *) allocate(sizeof(long));
*pointer = 0xDEEDEEEF;
I just don't quite get exactly how this works since a char is 1 byte while a long should be 4 and so how does something like this work when I need to allocate 4 spots in the array to the one long pointer variable? Also feel free to give examples and explanations but please don't give away how the entire program should work as I would like to figure it out myself once I understand exactly how this part works. Thanks
Memory allocation is independent of type i.e whether it is long/char.etc But thing is, it is quantified on "bytes". And char is the only data type which takes one byte memory.
Its on your program how you treat the allocated memory. For ex
char s[4]={0,0,0,'A'};
int *p = (int*)s; //treating those 4 bytes as int
printf("%d",*p); //will print 65
I will suggest you to watch first 4-5 Stan-Ford Programming Paradigm lectures. Memory allocation is explained incredibly well in those lectures. You can also refer to Chapter 8 of The C programming language -by Denis Ritchie