Ch1 : 4- C/C++

Objectives : Walking along with C and C++

  • Looking C and C++ side by side
    • allocating / freeing memories: The input are saved and managed distinctively.
      • with C : malloc(10*sizeof(int)) and free(dtata_type)
      • with C++ :
        • non-array type 
          • int *n1 = new int; // dynamically allocate an integer
            *n1 = 5; // assign 5 to this integer
            delete n1; // freeing memory
        • arrays
          int x = 10;
          int * n2 = new int[x];// allcate an array
          n2[5] = 5;// assign 5 to n[5] element
          delete[]n2;// freeing memory
    • Comparing "printf" of C and "cout" of C++ : the output can be similar but these two functions are not similar
      • C : prints only with "printf";
      • C++: can print with "cout and "printf"; printf is a function and prints faster, but not type safe. The object "cout" belongs to "iostream".
  • Files Used :
    • compare_c_cplus1.cpp -- did not release memory, may cause memory leak
    • compare_c_cplus2.cpp --release memory with free(n1) and delete[ ] n2;
  • Code : compare_c_cplus1.txt
 

Step: 1 Create two source files.
 

Step: 2 Edit and save Source file

Note that in the example shown below, the function," free (pointer-variable)", of C language, and the object "delete[]" of C++ language were used to free up the memories.

Step: 3 Runtime Views:

a) Example of not releasing memories:  Allocating memories with "malloc(10*sizeof(int))" function of C language , and "new[]" object of C++ language.

b) Free and Reuse Memory Location:  Releasing memories with "free()" function and "delete[]" object, with C and C++ ways respectively.

Step: 4 Brief Discussion: The pair of functions, "malloc()" and "free()"  of C, and the pair objects "new[]" and delete[]" of C++ , are used to allocate and free memories in the above examples; but though a different mechanisms.

Special Notes To: Allocating Memory Storage

In your computer several blocks are reserved for few specific reasons.

  • The blocks allocated for parameters used by operating system.
  • A block of read only memories for Basic I/O system( BIOS).
  • Blocks for display buffers.
  • Blocks for new programs or applications

Both C and C++, allow allocate and deallocate memories created dynamically using pointers. Heap is part of the memory managed by your operating system where dynamically created data like string and arrays are placed. The purpose of a malloc() function and it's counterpart free() implementation is to find an free space of memory on the heap  and return that address for you so that you allocate the block of data and free up the allocated memory as soon as the task is completed.

http://stackoverflow.com/questions/240212/what-is-the-difference-between-new-delete-and-malloc-free  being edited

C / malloc or calloc  and  free

C++/ new /new []and delete/delete[]

Syntax : int n1 = (int *) malloc(sizeof(int));
                         free(n1);
Syntax : 
               int *n1 = new int;    delete(n1); // one object
               int *n1 = new int[5] delete [] n1; // an array/vector
   
  • Allocates/release memory
  • Allocating array requires manual calculation of space.
  • May throw NULL on failure
  • Allocate/release memory  for an object from a pool called free-store.
  • The compiler calculates the size.
  • new operator  will not process a NULL (throws the bad_alloc on failure)
  • C++ uses ~destructor function to destroy the object created with new operator.
  • malloc() returns a void pointer (void *), which indicates that it is a pointer to a region of unknown data type. The lack of a specific pointer type returned from malloc is type-unsafe behavior, The function malloc allocates the memories based on byte count but not on type.
  • The new operators returns a pointer to the newly allocated memory;
  • new attempts to allocate enough memory on the heap for the new data.
  • In C++ new operator allows "Dynamic memory allocation", which allows us to allocate memory of whatever size we want when we need it on the fly.
     
  • Reallocating larger chunk of memory simple. the realloc() function change the size of a memory-block, previously allocated with malloc() or calloc()
  • In contrast to C/ realloc() function, it is not possible to directly reallocate memory allocated with new[]. To extend or reduce the size of a block, one must allocate a new block of adequate size, copy over the old memory, and delete the old block.
  • .malloc/free can NOT be overridden legally
  • operator new/delete can be overridden legally
  • constructor/destructor used to initialize or destroy the object
  • The parameter or free(ch1) is a void pointer, frees the memory hold-ups by calloc/realloc() functions.
  • new add data on heap and may cause problem. Make sure you need to use heap, or stack will do.
  • When you use the new keyword you are putting data on the heap. The heap is a large chunk of memory where objects (which can be big in size) reside. The stack is for simple data types like simple integers, chars etc
  • A stack is a last-in, first-out (LIFO) structure.

Collected information

Reference : http://www.dreamincode.net/forums/topic/226166-microsoft-beware-of-the-heap-monster/

Avoid coding like

char * array[1000];
for ( int x = 0; x < 1000; x++ ) array[x] = new char;

This would require 32000 bytes of heap space used to hold 1000 bytes of information! Put it another way, I'll lend you $1000 so you owe me $32000! Now, you may think that no developer would be so stupid as to use code like that, but I can assure you I have seen such code on many occasions written by different developers.

It is far better to allocate a character array of 1000 bytes which would take 1024 bytes of heap space.