Tag Archives: malloc

Replace C++ malloc with Fast Fixed Block Memory Allocator

Replace C++ malloc with Fast Fixed Block Memory Allocator

This is an interesting memory processing replacement but would be interested here from the experts

http://www.codeproject.com/Articles/1083210/An-Efficient-Cplusplus-Fixed-Block-Memory-Allocato

http://www.codeproject.com/Articles/1084801/Replace-malloc-free-with-a-Fast-Fixed-Block-Memory

Also the benchmarks looks pretty impressive on these articles

Join my FREE newsletter to see what other C++ tips there are for speeding up your automated trading

 

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ concise cheat sheet on operators, malloc, calloc, storage classes, and storage qualifiers

C++ concise cheat sheet on operators, malloc, calloc, storage classes, and storage qualifiers

Operators
What is assignment operator?
Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy)
What is conversion operator??
class can have a public method for specific data type conversions.
for example:
class Boo
{
double value;
public:
Boo(int i )
operator double() { return value; ]
};
Boo BooObject;
double i = BooObject; // assigning object to variable i of type double. now conversion operator gets called to assign the value.
The postfix version of operator++() has a dummy parameter of type int. The prefix version does not have dummy parameter.
What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don’t define one.?? default ctor, copy ctor, assignment operator, default destructor, address operator
Memory Related

New and delete allocate memory. New calls constructor while malloc does not.
Reference: has to be initialized when declared
cannot reseat once refer to an object
cannot do arithmetic operation, int& ref=&a, ref++ will be wrong
cannot be assigned with NULL
cannot take the reference of a reference variable, pointter of pointer is possible
As a general rule,
Use references in function parameters and return types to define attractive interfaces.
Use pointers to implement algorithms and data structures.

Hard/Deep Copy is copying the values from one structure to another.If there are pointers in the structure, then the second structure also points to the same pointer location as in the first one. To make a hard copy, you must wite a copy constructor and overload the assignment operator.

Shallow copy is copying bit by bit, If there are pointers in the structure to be copied,then a new memory location is created and data is copied to that location.

Note that calloc has 2 arguments while there is 1 in malloc.
void *malloc( size_t size ); void * calloc ( size_t num, size_t size );.

Malloc reduces requesting new memory from OS by recycling the freed memory space. It uses Free List to keep track of the freed memory. When free(ptr) is called, the allocator looks at the header/footer of the memory block. The header of the memory block contains enough information (such as total bytes, status(freed/allocated), etc..) to remove it. ) This free list needs not to be a single linked list generally a balanced tree .

Why should malloc never be directly used to dynamically allocate instances of a class?

malloc just allocates memory for objsize* but it doesn’t initialize the class (i.e invoking constructor and performing initialization). whereas “new” allocates the memory for the objsize* and implicit invoke the constructor (in case no constructor exist, then default is considered) to initialize the class.
What is diff between malloc()/free() and new/delete?
malloc allocates memory for object in heap but doesn’t invoke object’s constructor to initiallize the object.
new allocates memory and also invokes constructor to initialize the object.
malloc() and free() do not support object semantics
Does not construct and destruct objects
string * ptr = (string *)(malloc (sizeof(string)))
Are not safe
Does not calculate the size of the objects that it construct
Returns a pointer to void
int *p = (int *) (malloc(sizeof(int)));
int *p = new int;
Are not extensible
new and delete can be overloaded in a class
“delete” first calls the object’s termination routine (i.e. its destructor) and then releases the space the object occupied on the heap memory. If an array of objects was created using new, then delete must be told that it is dealing with an array by preceding the name with an empty []:-
Int_t *my_ints = new Int_t[10];

delete []my_ints;

Char a[]=””; is size of 2 characters which is ‘\0’ and null. The trick is the memory allocated two characters of space. Char a[]=”hello”; // 6 bytes
Char *a=”hello”; //4 bytes

IF we are decreasing the size of vector, or if we are increasing the size but the vector still has enough capacity, there’s no need to allocate memory. When capacity is not enough, the function will cause a reallocation: 1). allocate contiguous memory elsewhere, which can hold the original vector plus new elements. if such a space is not available, return false; 2) copy the original vector and then reclaim the space; 3) add new elements at the back. Sorry, when reallocation is not successful, this function will not return a false, it’s a void function. Instead, a bad_alloc exception will be thrown.
Memory allocation depends on ‘best fit’ and ‘first fit’.
Stack:
– local variables (variables declared inside a function) are put on the stack – unless they are also declared as ‘static’ or ‘register’
– function parameters are allocated on the stack
– local variables that are declared on the stack are not automatically initialized by the system so they usually have garbage in them until you set them
– variables on the stack disappear when the function exits (thus, if a function is called multiple times, it’s local variables and parameters are recreated and destroyed each time the function is called end exited).
Heap:
– declared variables (as opposed to dynamically created ie new, malloc) are created on the heap before program execution begins, they exist the entire life of the program (although scope may prevent access to them – they still exist) and they are initialized to all zeros
– global variables are on the heap
– static local variables are on the heap (this is how they keep their value between function calls)
– memory allocated by new, malloc and calloc are on the heap
Code Segment
Data Segment:
– Unintialized Data (bss block started by symbol) – Static variables (before program initializes, these variables will be initialized zero.
– initilaized Data (your int i =0)
Templates
template
T sum(T* arr, int num){

T sum=0;
for(int i=0;i
int Product (T1 a, T2 b, T3 c) { return a * b * c; }
You cannot return an int since the parameter is type T, you do not know if it is an int, so you must return a type T.
Storage classes and storage qualifiers
auto
register
static
extern
auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block
register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance
static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution
extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.
What are storage qualifiers in C++ ?
They are..
const
volatile
mutable
Const keyword indicates that memory once initialized, should not be altered by a program.
volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.
mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { “Satish Shetty”, 1000 }; //initlized by complier
strcpy ( MyStruct.name, “Shilpa Shetty”); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

How C++ allocators work just like malloc and free

How C++ allocators work just like malloc and free
In the C++ standard, the default allocator for objects of type T (cunningly known as allocator) offers the typedefs allocator::pointer and allocator::reference, and it is expected that user-defined allocators will provide these typedefs, too. Let’s be explicit about this: it means that portable allocators may not have any nonstatic data members, at least not any that affect their behavior. None. Nada. That means, for example, you can’t have one SpecialAllocator that allocates from one heap and a different SpecialAllocator that allocates from a different heap. Such allocators wouldn’t be equivalent, and STL implementations exist where attempts to use both allocators could lead to corrupt runtime data structures. the most common forms of operator new and allocator::allocate:
void* operator new(size_t bytes);
pointer allocator::allocate(size_type numObjects);
// recall that “pointer” is a typedef
// that’s virtually always T*
Balanced binary search trees are use associate containers.
template > // implementation
class list{
private:
Allocator alloc; // allocator for objects of type T
struct ListNode{ // nodes in the linked list
T data:
ListNode *prev;
ListNode *next;
};

};
When a new node is added to the list, we need to get memory for it from an allocator, but we don’t need memory for a T. we need memory for a ListNode that contains a T. That makes our Allocator object all but useless, because it doesn’t allocate memory for ListNodes, it allocates memory for Ts.
Allocator::rebind::other
rebind takes a single type parameter, U, and defines nothing but a typedef, other. other is simply a name for A. As a result, list can get from its allocator for T objects (called Allocator) to the corresponding allocator for ListNode objects by referring to Allocator::rebind::other.
Allocator can be slow and a waste of memory. This is how to use an allocator where you have supposed allocators like malloc and free:
void* mallocShared(size_t bytesNeeded);
void freeShared(void *ptr);
template
class SharedMemoryANocator {
public:

pointer allocate(size_type numObiects, const void *localityHint = 0)
{
return static_cast(mallocShared(numObiects* sizeof(T)));
}
void deallocate(pointer ptrToMemory, size_ type numObjects)
{
freeShared(ptrToMiemory);
}

};
You could use SharedMemoryAllocator like this:
// convenience typedef
typedef vector >
SharedDoubleVec;

{ // begin some block
SharedDoubleVec v: // create a vector whose elements
// are in shared memory
… // end the block
}
the runtime system uses for all normal stack-based objects. That’s almost never shared memory. To put both v’s contents and v itself into shared memory, you’d have to do something like this:
void *pVectorMemory = // allocate enough shared
mallocShared(sizeof(SharedDoubleVec)); // memory to hold a
// SharedDoubleVec object
SharedDoubleVec *pv = // use “placement new” to
new (pVectorMemory) SharedDoubleVec; // create a SharedDoubleVec
// object in the memory;
41
// see below
// use the object (via pv)

pv->~SharedDoubleVec(); // destroy the object in the
// shared memory
freeShared(pVectorMemory); // deallocate the initial
// chunk of shared memory

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview questions on memory like malloc, new, delete, heap, stack, hard copy

C++ interview questions on memory like malloc, new, delete, heap, stack, hard copy

This is easily the most complex and important section of any C++ interview.

Memory related:
. What’s the difference between a pointer and a reference?
2. What’s the difference between a class and a struct?
3. How do you allocate memory in C++? What’s the difference between malloc and new?
12

1. pointer could be NULL while reference must be alias for some object; pointer can be reassigned to point to other objects, while reference must always be the alias for the same object.

2. struct has no member function? not sure tho

3. new and delete. new calls constructors while malloc does not

2. struct and class are same except that struct has a member as public by default while class has a member as private by default.

agree, I was wrong

struct can’t have functions like a class
in c++ it can. public by default (struct) private by default (class) only difference
venkat on September 27, 2009 |Edit | Edit

You can always add another difference to yours…

struct(s) inheritance is by default public where as
class(s) inheritance is by default private.

inheritance in struct is public by default and in class its private by defualt

In case of C#, Structures and Classes are different because structures are allocated on stack and class objects are allocated on heap. Structures does not support inheritance, as they’re implicitly sealed. Furthermore, no member function of a Structure can be virtual, also destructors and finalize methods cannot be written for structures.

the only difference between C++ struct and class is that the default data type in class is private whereas its public in case of struct, apart from that rest of the things are same in C++. this is _the only_ difference…

A reference is essentially a pointer that has already been de-referenced for you.

reference is a syntactic sugar when compared to a pointer

Reference: has to be initialized when declared
cannot reseat once refer to an object
cannot do arithmetic operation, int& ref=&a, ref++ will be wrong
cannot be assigned with NULL
cannot take the reference of a reference variable, pointter of pointer is possible
As a general rule,
Use references in function parameters and return types to define attractive interfaces.
Use pointers to implement algorithms and data structures.

What is hard copy and shallow copy?

# A shallow copy generally means copying bits from one memory block to another.
# A deep copy generally means recursively copying variables in a nested structure, or objects in a nested object.

1. http://tinyurl.com/llpes6
2. http://portal.acm.org/citation.cfm?doid=782941.782990

HardCopy is copying the values from one structure to another.If there are pointers in the structure, then the second structure also points to the same pointer location as in the first one.

Shallow copy is copying bit by bit, If there are pointers in the structure to be copied,then a new memory location is created and data is copied to that location.

Hard copy – a print-out.

Shallow copy – a bit by bit copy of data type’s instance without copying aggregated structure or class instances.
Reply to Comment
creation on December 09, 2009 |Edit | Edit

A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied — the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.

Explain the difference between calloc and malloc
Two differences:

1. No. of arguments accepted (2 in calloc, 1 in malloc).
2. Initialising of memory to zero (in calloc)

Explain the functionality of malloc…If a pointer ptr is pointing to array of 100 bytes and free(ptr) is called..then How the compiler knows that 100 bytes are to be removed…Explain any other way to optimize this.
malloc is a memory allocator which manages the memory use requested by user.
It reduces requesting new memory from OS by recycling the freed memory space. It uses Free List to keep track of the freed memory. When free(ptr) is called, the allocator looks at the header/footer of the memory block. The header of the memory block contains enough information (such as total bytes, status(freed/allocated), etc..) to remove it.

Coalescing the freed memory with its neighbor freed memory can optimize the memory use. It also reduces the external fragmentation.
Generally with the traditional memory managers some leading bytes (2 bytes) are allocated .Now when user call free(addr) it tries to do the addr-2 and get the size of the block .Then it just add this block to the available free list .Where in the free list it is added depends upon the memory manager(first fit , best fit and worst fit) also this free list needs not to be a single linked list generally a balanced tree .
¬
char a[] = ” “;
Q. What will be sizeof(a)
IF initialised string is empty it seems size should be 1 and if it has a space it should be 2
Actually I was quite surprised at the answer I got for this one. I would have thought that the value returned would be the size of (char *) the pointer. However, I compiled the following program:

#include

main () {
char a[] = ” “;
char b[10];

printf (“Sizeof(a) = %d\n”, sizeof(a) );
printf (“Sizeof(b) = %d\n”, sizeof(b) );
}

The resulting output was as follows:

Sizeof(a) = 2
Sizeof(b) = 10

What can I say but… go figure

for array a, it contains two char, one is null , the other is ‘\0′
for array b, it only has ten characters’ memory space.
dfmcla on March 01, 2010 |Edit | Edit

The question was not:
How many characters are in the array?
it was:
What will sizeof()?

In the example program I gave, sizeof(a) returns the value 2 while sizeof(b) returns the value 10
each char is 1 byte
so the first one is 2 byte; the second one is 10 byte

the trick here is you should know the first array allocates two characters space

@dfmcla…
if we define char a[], then ‘a’ would store the address of the string….but ‘a’ itself is an array…hence, sizeof(a) would give size of this array..
now if we define char* a=new char[10], then, sizeof(a) would give size of a char pointer(same size as int and float pointer)…coz here ‘a’ is a char pointer….
@dfmcla…
if we define char a[], then ‘a’ would store the address of the string….but ‘a’ itself is an array…hence, sizeof(a) would give size of this array..
now if we define char* a=new char[10], then, sizeof(a) would give size of a char pointer(same size as int and float pointer)…coz here ‘a’ is a char pointer….

sizeof(a) will be 4 bytes i.e size of pointer.

this ans is wrong. sizeof(a) is 1 … note that ‘a’ is a character array, not character pointer.

Okay I think only pointer will be returning the sizeof(char *). Arrays will be just returning the size of the array. check the below code.

#include

main () {
char a[] = ” “;
char b[10];
char *c;
char *d = b;

printf (“Sizeof(a) = %d\n”, sizeof(a) );
printf (“Sizeof(b) = %d\n”, sizeof(b) );
printf (“Sizeof(c) = %d\n”, sizeof(c) );
printf (“Sizeof(d) = %d\n”, sizeof(d) );
}

Sizeof(a) = 2
Sizeof(b) = 10
Sizeof(c) = 4
Sizeof(d) = 4
The length of array is calculated as sizeof(a)/sizeof(a[0]);
‘a’ is an empty string i.e., points to ‘\0’ which is defined as integer 0
hence it is sizeof(‘\0’) which is sizeof(0) which is sizeof(int) = 2
bwc on March 18, 2010 |Edit | Edit

sorry but there needs to be some correction in your statement above.
sizeof(int).. is mostly 4 (for 4 byte).. and again.. depends on your machine platform.

If sizeof(int) is 2 for your computer, hope you get a new computer because thats from the old ages. sizeof(\0) also is not sizeof(0) because zero is an integer which should be 4.

The answer for sizeof(a) is true ..because for the declaration -> char a[] = ” “, the answer is whatever is in the double quotes + NULL char.

For sizeof(p) where declaration is char *a, it will always be 4 for 32-bit machines or 8 for 64-bit machines, because the asterisk is really a pointer where as the [] symbol denotes and array with.

In order words there is a difference in sizeof for
char a[] = “hello”;
and
char *p = “hello”;
where
sizeof(a) = 6
sizeof(p) = 4

Read “Pointers on C” book if you want to know more as it depicts a diagram. You will not know your C well if you don’t read that book.
Raul Gonzales on March 21, 2010 |Edit | Edit

Hello guys,
I don’t think any of you is right!!!!
For the simple reason that you are arguing, and mahesh is too arrogant to explain why things are as they are!
I am new to C but study very hard!
No one pointed out that the answer depends on compiler.
I was surprised to see, my compiler “Miracle C” gives the following output after the program is ran:

program(same as bala’s code here):

#include

main () {
char a[] = ” “;
char b[10];
char *c;
char *d = b;

printf (“Sizeof(a) = %d\n”, sizeof(a) );
printf (“Sizeof(b) = %d\n”, sizeof(b) );
printf (“Sizeof(c) = %d\n”, sizeof(c) );
printf (“Sizeof(d) = %d\n”, sizeof(d) );
getchar();

}

output:

Sizeof(a) = 0
Sizeof(a) = 10
Sizeof(a) = 2
Sizeof(a) = 2

Now, since mahesh is such an expert, can he explain the above!!!!
Also Miracle C will show:

char arr[]=”Hello”;

sizeof(arr) will show to be 0;

OK experts, please enlighten me, because I do not know why, but this is the output I get!!!!!!!!!
Thank you!

Dude! change ur compiler to GCC, otherwise u wont get any interviews..Miracle C seems to be so far from standards! also sizeof(pointer) is 2 for your computer shows that it is 16 bit.

If I create an object of class Foo, and send its address and sizeof to memset and set it all to 0, will it work? I answered yes, it ll set it to 0.
then he asked, if everything sets to 0, will u still be able to call functions? i answered yes, but if the function uses any data, it might not work, as data would have been corrupted.
he asked, will any function not work? yes, if there are virtual functions, call to virtual functions will fail, as pointer to vtable will be corrupted.

Memory Resize Function
Memory Resize Function
Lets say contiguous memory is not available for vector’s elements and it is occupied by something else. How does the resize function of vector allocate memory to be contiguous allocation?

if we are decreasing the size of vector then there is no need to reallocate the vector.
If we are increasing the size of vector and there is no contiguous memory then vector won’t get allocated … it will return error…..
IF we are decreasing the size of vector, or if we are increasing the size but the vector still has enough capacity, there’s no need to allocate memory. When capacity is not enough, the function will cause a reallocation: 1). allocate contiguous memory elsewhere, which can hold the original vector plus new elements. if such a space is not available, return false; 2) copy the original vector and then reclaim the space; 3) add new elements at the back.
sorry, when reallocation is not successful, this function will not return a false, it’s a void function. Instead, a bad_alloc exception will be thrown.
vivi,
so do you mean if contigeous memory is not available then vector resize function throw errors ?

Memory is allocated some where else(if it is available) and the contents of this vector are copied into that memory. Memory allocation depends on two strategies “first fit” or “best fit”. Don’t forget that java is build up on “C”.

where is global variable (defined outside any function or class) allocated, heap or stack?
It’s in the data segment of the code
neither… global v is allocated in static
Stack:
– local variables (variables declared inside a function) are put on the stack – unless they are also declared as ‘static’ or ‘register’
– function parameters are allocated on the stack
– local variables that are declared on the stack are not automatically initialized by the system so they usually have garbage in them until you set them
– variables on the stack disappear when the function exits (thus, if a function is called multiple times, it’s local variables and parameters are recreated and destroyed each time the function is called end exited).
Heap:
– declared variables (as opposed to dynamically created ie new, malloc) are created on the heap before program execution begins, they exist the entire life of the program (although scope may prevent access to them – they still exist) and they are initialized to all zeros
– global variables are on the heap
– static local variables are on the heap (this is how they keep their value between function calls)
– memory allocated by new, malloc and calloc are on the heap
by declared variable on heap , do you refer to
int i=10 in the main function ?
main()
{
int i=10;
}

I feel any variable decalred within a function goes to stack .here int i=10 goes to stack and if its outside main and decalred globally , it goes to heap.please correct me If i am wrong.

sandy on May 10, 2010 |Edit | Edit

No only dynamically allocated variables will be on heap. In this case, int i=0 is a global variable. This will be in the initialized data section.

Any process address space have following segments.

1. Stack Segment – Automatic variables or local varibles
2. Heap – Dynamically allocated variables
3. Code Segment
4. Data Segment
– Unintialized Data (bss) – Static variables (before program initializes, these variables will be initialized zero.
– initilaized Data (your int i =0)

can you give detail explanation how you will provide your own new operator

static variables are stored in the data segment or BSS of the process memory.
http://en.wikipedia.org/wiki/.bss
In computer programming, the name .bss or bss is used by many compilers and linkers for a part of the data segment containing statically-allocated variables represented solely by zero-valued bits initially (i.e., when execution begins). It is often referred to as the “bss section” or “bss segment”.
In C, statically-allocated variables without an explicit initializer are initialized to zero (for arithmetic types) or a null pointer (for pointer types). Implementations of C typically represent zero values and null pointer values using a bit pattern consisting solely of zero-valued bits (though this is not required by the C standard). Hence, the bss section typically includes all uninitialized variables declared at the file level (i.e., outside of any function) as well as uninitialized local variables declared with the static keyword. An implementation may also assign statically-allocated variables initialized with a value consisting solely of zero-valued bits to the bss section.
Typically, the program loader initializes the memory allocated for the bss section when it loads the program. Operating systems may use a technique called zero-fill-on-demand to efficiently implement the bss segment (McKusick & Karels 1986). In embedded software, the bss segment is mapped into memory that is initialized to zero by the C run-time system before main() is entered.
Some application binary interfaces also support an sbss segment for “small data”. Typically, these data items can be accessed by leaner code using instructions that can only access a certain range of addresses.
Historically, BSS (from Block Started by Symbol) was a pseudo-operation in UA-SAP (

what will be size of class and size of object of class.
class A{
int *p;
static int a; }
5

Is the size of the class and object always same ?Why is it so ?
If the class has static members, then these members are not stored in the object. Inspite of that will the class and object have the same size ?
I would say that for the class, the size of the static is taken into consideration, where as for the object you do not because static does not instantiate an object. So, in this case: size of the class would be 8 bytes and size of the object will be 4 bytes
What do you mean y size of a class..? Unless and until you instantiate, the memory will not be allocated right? Just class does not make sense right? Please clarify.
Yes, you are right. But, assuming that the object has been instantiated, the size of the class will be 8 bytes ‘on paper’ and 4 bytes for the object

you inadvertently overwrite some portion of memory that some pointer or a variable is
memory corruption, call stack corruption. In unix, scope is limited to these 2 inside a process. In RTOS, the corruption can span across multiple tasks/processes

what will be size of class and size of object of class.
class A{
int *p;
static int a; }
4
Is the size of the class and object always same ?Why is it so ?
If the class has static members, then these members are not stored in the object. Inspite of that will the class and object have the same size ?
I would say that for the class, the size of the static is taken into consideration, where as for the object you do not because static does not instantiate an object. So, in this case: size of the class would be 8 bytes and size of the object will be 4 bytes
What do you mean y size of a class..? Unless and until you instantiate, the memory will not be allocated right? Just class does not make sense right? Please clarify.
Yes, you are right. But, assuming that the object has been instantiated, the size of the class will be 8 bytes ‘on paper’ and 4 bytes for the object

:
how to tell if a stack grows up or down
Why should malloc never be directly used to dynamically allocate instances of a class?

malloc just allocates memory for objsize* but it doesn’t initialize the class (i.e invoking constructor and performing initialization). whereas “new” allocates the memory for the objsize* and implicit invoke the constructor (in case no constructor exist, then default is considered) to initialize the class.
What is diff between malloc()/free() and new/delete?
malloc allocates memory for object in heap but doesn’t invoke object’s constructor to initiallize the object.
new allocates memory and also invokes constructor to initialize the object.
malloc() and free() do not support object semantics
Does not construct and destruct objects
string * ptr = (string *)(malloc (sizeof(string)))
Are not safe
Does not calculate the size of the objects that it construct
Returns a pointer to void
int *p = (int *) (malloc(sizeof(int)));
int *p = new int;
Are not extensible
new and delete can be overloaded in a class
“delete” first calls the object’s termination routine (i.e. its destructor) and then releases the space the object occupied on the heap memory. If an array of objects was created using new, then delete must be told that it is dealing with an array by preceding the name with an empty []:-
Int_t *my_ints = new Int_t[10];

delete []my_ints;

what is the diff between “new” and “operator new” ?

“operator new” works like malloc.

Given that plenty of memory is available, how would you design a program that would hold information of about 3000 employees in a company?

HOW DO YOU START A PROFITABLE TRADING BUSINESS? Read more NOW >>>

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!