Wednesday, January 12, 2011

C++ : New and Malloc


This small article is for C++ beginners, who is familiar with C. The dynamic memory allocation with C will be done with Malloc library function. In C++ it will be done with an operator new. Don't be confused, new is not a function, but a operator like +.- etc.. Here I will give you some example of how we use malloc and new.

//declaring native type

int* i1 = new int;
delete i1;

int* i2 = (int*) malloc(sizeof(int));
free(i2); //declaring native type array

char** c1 = new char*[10]; // Array allocation
delete[] c1; // cleaning array allocation

char** c2 = (char**) malloc(sizeof(char)*10);
// Allocation a two dimensional array in C
free(c2);

Notes:
1- Since new/delete is an operator, you can overload it.

2- There is no alternative for C function realloc , in C++.

- You can use STL containers instead of new, if a realloc required( eg. std::vector<>::resize()).

- When explicit memory management is necessary, try to use smart pointers to make it easier and safer.

- Don't use malloc() or 'new' when containers or automatic variables can do the job.


3- new will call the appropriate construction to create the object. Similarly delete will call destructor.

4- No typecasting required for new.

5- malloc() returns NULL on failure while 'new' throws an exception.

6- malloc() allocates raw memory while 'new' constructs objects in the allocated space.
eg. shape * sp=new(12);



Sunday, January 9, 2011

C source code : Linked list operations

#include <stdio.h>
#include <stdlib.h>
typedef struct list* node;

struct list {
    node next;
    int data;
};

node create_node(int val)
{
    node new_node=(node)malloc(sizeof(node));
    new_node->data=val;
    return new_node;
}
void insert_node(node head, int val, int pos)
{
    while(head->data!=pos)
    {
        head=head->next;

    }
    node tmp=head->next;
    head->next=create_node(val);
    head->next->next=tmp;

}

void print_list(node head)
{
    while(head!=NULL)
    {
        printf("%d - ",head->data);
        head=head->next;
    }
}

int main()
{
    int i;
    printf("Linked List operation\n");
    node head=create_node(0);
    node start=head;
    for(i=1;i<=10;i++)
    {
        head->next=create_node(i);
        head=head->next;
    }
    head->next=NULL;
    print_list(start);
    printf("\n Print the list after insertion");
    insert_node(start,15,5);
    printf("\n");
    print_list(start);
    return 0;
}