Heap Array

Hello, I am new in C++ enviroment. I was a C programmer for 2 years. After knowing so much about it, I decieded to move to somthing bigger like Java or C++. I didn't like how Java work because basically I like to know everything going on under the hood. Anyway, I am here today to ask for your help about a heap allocation library that I have implemented using C++. I want to know if this library is useful in anyway or is there a standard library that does the same job.

Thank you in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 #ifndef HEAP_H
 #define HEAP_H

/* IMPORTANT: this library only works with printf and fails with std::cout */

#include <new>

template <class Any,const size_t N>
class Heap{
private:
	Any* cell;
public:
	Heap(){
		this->cell = new Any [N];
		for(register size_t i=0;i < N;i++) /* loop and initialze heap cell with null */
			this->cell[i] = (Any) 0;
	}
	void set(const size_t i,Any cell){
		if(i < N) /* if not heap overflow, set the cell */
			this->cell[i] = cell;
		/* else do nothing */
	}
	Any get(const size_t i){
		if(i < N) /* if not heap overflow, return the cell */
			return this->cell[i];
		return (Any) 0; /* else return null */
	}
	void swap(const size_t x,const size_t y){
		if(x < N and y < N){ /* if not heap overflow, swap cells */
			Any t = this->cell[x];
			this->cell[x] = this->cell[y];
			this->cell[y] = t;
		}
	}
	void copy(const size_t dest,const size_t src){
		if(dest < N and src < N) /* if not heap overflow, copy to dest cell, src cell */
			this->cell[dest] = this->cell[src];
	}
	~Heap(){
		delete [] this->cell; /* free the heap */
	}
};
#endif /* HEAP_H */
What do you mean it doesn't work with std::cout? Why not? It seems to have nothing to do with ostream.

size_t is not a built-in type. You need to include at least one of the headers that defines it, such as <cstddef> or <cstdlib>. And technically it's std::size_t (unless you include the C-header as <stddef.h>). In gcc, <iostream> defines it but <new> does not.

"const" makes no sense on a template parameter; they aren't variables.

"const" has very little purpose in all the other places you use it. It's main purpose it to promise not to modify the caller's data when it's passed as a pointer or reference.

"register" is totally useless. The compiler will figure out it's own optimizations. In fact, it's been deprecated for a long time and was removed from the current standard (C++17), although it's still a reserved word.

(Any) 0 is very strange. Why would you think that would work with arbitrary objects?

In what sense is this a "heap"? It looks like an array. A better name would be Array. But it's missing an awful lot of code that a fully-developed class would have. std::array does more and is standard.
Last edited on
What do you mean it doesn't work with std::cout? Why not? It seems to have nothing to do with ostream.

Sorry, my bad I forgot about the comment I wrote. What I was meaning by it doesn't work with std::cout is that when you use set(0,NULL) for example std::cout wont print anything and will terminate. But when I used printf it works perfectly.


In what sense is this a "heap"? It looks like an array


Isn't using new operator allocate space in the heap?
I want to know if this library is useful in anyway or is there a standard library that does the same job.
A similar container is std::array.

Interesting at this topic are the 'new' and 'delete' operator. Imho they are implemented by 'malloc' and 'free' via operator overloading - look at https://en.cppreference.com/w/cpp/memory/new/operator_new
Here a code snipping from there:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdio>
#include <cstdlib>
// replacement of a minimal set of functions:
void* operator new(std::size_t sz) {
    std::printf("global op new called, size = %zu\n",sz);
    return std::malloc(sz);
}
void operator delete(void* ptr) noexcept
{
    std::puts("global op delete called");
    std::free(ptr);
}
int main() {
     int* p1 = new int;
     delete p1;
 
     int* p2 = new int[10]; // guaranteed to call the replacement in C++11
     delete[] p2;
}


Last edited on
What I was meaning by it doesn't work with std::cout is ...

I still don't understand this. A full example would help.

Isn't using new operator allocate space in the heap?

Yes, I suppose that's true, but allocating something on the heap doesn't make that thing itself a heap. "Heap" seems like a strange name to me. I guess it's not exactly a "dynamic" array since you can't resize it. So maybe HeapArray. And I suppose that makes it different from std::array since a std::array's data is not allocated on the heap (unless the user allocates the whole thing dynamically).
Last edited on
A similar container is std::array.


I checked it, and it was helpful thanks.


Interesting at this topic are the 'new' and 'delete' operator. Imho they are implemented by 'malloc' and 'free' via operator overloading - look at https://en.cppreference.com/w/cpp/memory/new/operator_new


Yeah I was wondering why there is new like malloc and delete like free but there are no realloc.
I still don't understand this. A full example would help.



- Ex:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <stdio.h>
#include "heap.h"

int main(void){
    Heap<const char*,128> heap;
    heap.set(0,NULL);
    std::cout << heap.get(0);     /* this won't print anything, and in some situation may crash */
    printf("%s\n",heap.get(0));   /* this will print null on the screen and no crash */       
    return 0;
}
Last edited on
It's unkind to post code that you didn't bother to run yourself. Anyway, after fixing the syntax error, for me the cout simply prints nothing while the printf segfaults. It's called "undefined behavior" and you really can't predict what will happen with different compilers/systems. Anyway, that would be the user's fault, not a problem with your "Heap".

Please stop using /* */ comments for single lines. Even C has // these days!

Here's an example you should consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <string>

class Object {
    std::string s;
public:
    Object() {}
    Object(std::string s) : s(s) {}
};

int main() {
    Heap<Object, 10> h;
    h.set(2, Object("hi"));
}


It's unkind to post code that you didn't bother to run yourself.


That's right. My bad xd.


for me the cout simply prints nothing while the printf segfaults.


That's weird, I am using linux system and printf() always print (null) for me.


It's called "undefined behavior" and you really can't predict what will happen with different compilers/systems. Anyway, that would be the user's fault, not a problem with your "Heap".


To be honest I didn't test it very much. I tried to test it my best and untill now I didn't see printf fails once. It could be because I am not targeting the right tests for it. Idk


Please stop using /* */ comments for single lines. Even C has // these days!


Why? it looks cleaner and much easier to read for me. I know some people might prefer the other way, but still I like it and I will keep using it xd.



Here's an example you should consider:


In this or simillar situations I believe you can use it in this way:
(1): create object variable.
(2): make the heap as object pointer.
(3): pass object refrence.
(4): get object refrence.
1
2
3
4
5
6
7
int main(void){
    Object object("hi");        /* (1) create object */
    Heap<Object*,10> h;    /* (2) create object pointer */
    h.set(2,&object);           /* (3) set object refrence */
    h.get(2);   /* (4) get object refrence */
    return 0;
}




Last edited on
Whatever. Do it your way then.
Please stop using /* */ comments for single lines. Even C has // these days!

// comments have one big problem.
When you paste code and the editor needs to insert line breaks in the comment it will break the code.
I wonder if nobody had error messages because of this.
When you paste code and the editor needs to insert line breaks in the comment it will break the code.

I haven't had this problem, because I haven't used any such automatic line breaking tool (i.e. that inserts a newline character, not just displaying things so that it looks like multiple lines). If it breaks the code I would say it's a buggy tool.

I kind of like how /* */ comments look, at least when used inside/after statements, but I personally avoid sprinkling them inside the code because it's so annoying in case I want to comment out some section of the code. It would be nice if C++ allowed nested comments.
Last edited on
Topic archived. No new replies allowed.