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;
}

Tuesday, December 21, 2010

C code: A small program to convert decimal number to binary digits.

Hi,

Here its a small recursive function, which will convert a decimal value to binary digits.

#include <stdio.h>

void convert_binary(int a)
{
  if(a!=0)
    {
        convert_binary(a/2);
        printf("%d",a%2);
    }
    else
    {
        return ;
    }
}

int main()
{
    printf("Hello world!\n");
    convert_binary(130); // Here this recursive function will convert 130 to binary digits.
    return 0;
}

If you feel its good, give me a thanks !!!

 

C Threads : Two synchronized threads to print alternate numbers.

Here, i was trying to print alternate numbers starting from 0 to 11. I have two threads, one will always prints odd numbers and other will print only even number.

My intension is to print odd and even alternately. To ensure the synchronization, i am using MUTEXES.

Sample code :
pthread_mutex_lock (&mutexsum);
gCount++;
std::cout<<gCount<<endl;
pthread_mutex_unlock (&mutexsum);

Full version of the code is as below. Here I use pthread libraries to create the threads.
My reference  : https://computing.llnl.gov/tutorials/pthreads/.

#include <iostream>
#include<stdio.h>
#include <pthread.h>
using namespace std;
pthread_mutex_t mutexsum;
int gCount=0;

void *odd(void* ptr)
{
while(gCount<=10)
{
   if(gCount%2==1) //If even
   {
        pthread_mutex_lock (&mutexsum);
        gCount++;
        std::cout<<gCount<<endl;
        pthread_mutex_unlock (&mutexsum);
   }
}
}

void *even(void* ptr)
{
while(gCount<10)
{
   if(gCount%2==0) //If even
   {
        pthread_mutex_lock (&mutexsum);
        gCount++;
        std::cout<<gCount<<endl;
        pthread_mutex_unlock (&mutexsum);
   }
}
}

int main()
{

    pthread_t T_even, T_odd;
    int T_rt1,T_rt2;
    void *status;
    pthread_mutex_init(&mutexsum, NULL);
    std::cout << "Hello world!" << endl;
    int i=0; // this variable has no significance
    T_rt1= pthread_create(&T_odd,NULL,odd,&i); // here variable i has no significance. it can be null also. I am passing it as a trial
    T_rt2=pthread_create(&T_even,NULL,even,&i);

    pthread_join(T_odd,&status);
    pthread_join(T_even,&status);

    pthread_exit(NULL);
    return 0;
}

Send me your comments.

Tuesday, December 7, 2010

C Code: Functions to read a line from file, removing leading and trailing spaces from a string token and get token string.

/******************************************************************************
*
* Function Name: read_line
*
* Description: get one line from /etc/passwd file. If there is a line contains
* more than LINE_MAX characters, it will ignore it and read the
* next line. It also handles continuation character '\'. It always
* leaves (or inserts) \n\0 at the end of the line.
*
* Parameters:
* FILE *f: file ptr points to /etc/passwd file
* char *buffer: char array
* size_t bufeln: length of buffer
*
* Return Value:
* int : It returns the length of the line read, excluding the \n\0.
*
******************************************************************************/
static int read_line(
FILE *f,
char *buffer,
size_t buflen)
{
int linelen = 0;
char c;
int curlen = 0;
char *ret, *tempbuf;

tempbuf = buffer;
while (1) {
tempbuf += (unsigned)curlen;
/* buffer over flow, skip this long line */
if (tempbuf >= (buffer + buflen - 1))
{
do {
c = getc(f);
if (feof(f)) {
return (-1);
}
} while (c != '\n');
linelen = 0;
tempbuf = buffer;
curlen = 0;
}
ret = fgets(tempbuf, linelen == 0 ?
buflen : buflen - (unsigned)linelen, f);
curlen = strlen(ret);
linelen += curlen;
switch (ret == NULL ? EOF : ret[curlen - 1]) {
case EOF:
if (linelen == 0 ) {
/* The file was empty */
linelen = -1;
} else if (buffer[linelen] == '\\') {
/* We expected another line to append to previous
line as indicated by a trailing backslash, but the
file ended */
linelen = -1;
} else {
/* The file contained one line, and all is well */
buffer[linelen ] = '\n';
buffer[linelen + 1 ] = '\0';
}
return (linelen);
case '\n':
if (curlen > 1 &&
ret[curlen - 2] == '\\') {
curlen -= 2;
linelen -= 2;
} else {
ret[curlen - 1] = '\n';
ret[curlen ] = '\0';
return (linelen - 1);
}
break;
default:
break;
} /* case */
}
/*NOTREACHED*/
}

/******************************************************************************
*
* Function Name: gettok
*
* Description: parse one line read from /etc/passwd file, return pointer to the
* next passwd entry field
* Parameters:
* char **line_addr: address of the pointer that point to an array
*
* Return Value:
* char *p : pointer to an array
*
*****************************************************************************/
static char *gettok (char **line_addr)
{
char *q = *line_addr;
char *p = q;
while (*p && *p != ':' && *p != '\n')
p++;
if (*p == '\n')
*p = '\0';
else if (*p != '\0')
*p++ = '\0';
*line_addr = p;
return (q);
}

/******************************************************************************
*
* Function Name: rm_leading_and_trailing_blank
*
* Description: Removes all the leading and trialing blanks in a string token.
* A string " This is a test " will be formatted to
* "This is a test"
*
* Cases like empty character string and character string with
* just a space or spaces are also covered. A string " "
* will be reduced to ""
*
* Parameters:
* target_string: string token.
*
* Return Value: None
*
*****************************************************************************/
static void rm_leading_and_trailing_blank(char *target_string)
{

char * mover = target_string;
char * current = target_string;

while (*mover != '\0' && (*mover == ' ' || *mover == '\t'))
mover++;

while(*mover)
{
*current = *mover;
current++, mover++;
}
*current = '\0';
current--;
while ( current >= target_string &&
(*current == ' ' || *current == '\t' || *current == '\n'))
{
*current='\0';
current--;
}

}

Tuesday, October 12, 2010

HP-UX Directory Server components


Directory Server 8.1 is comprised of several components, which work in tandem:
• Directory Server
The Directory Server is the core LDAP server daemon. It is compliant with LDAP v3 standards. This component includes command-line server management and administration programs, and scripts for common operations like export and backing up databases.

• Directory Server Console
The Directory Server Console is the user interface that simplifies managing users, groups, and other LDAP data for your enterprise. The Console is used for all aspects of server management, including making backups; configuring security, replication, and databases; adding entries; and monitoring servers and viewing statistics.

• Administration Server
The Administration Server is the management agent that administers Directory Servers. It communicates with the Directory Server Console and performs operations on the Directory Server instances. It also provides a simple HTML interface and on-line help pages. There must be one Administration Server running on each machine that has a Directory Server
instance running on it.

• Port numbers
The Directory Server setup requires two TCP/IP port numbers: one for the Directory Server and one for the Administration Server. These port numbers must be unique. The Directory Server instance (LDAP) has a default port number of 389(non-secure, secure port is 636) . The Administration Server port number has a default number of 9830. Alternatively, you can assign any port number between 1025 and 65535 for the Directory Server and Administration Server ports; you are not required to use the defaults or the randomly-generated ports.

Thursday, September 16, 2010

Using C functions like malloc in C++.


#include iostream

using namespace std;
extern "C"
{
int puts(const char *); // Using C style functions in Cpp.
void * malloc(std::size_t);
}
int main()
{
puts("helo world ! ");
int *p;
p=(int *)malloc(sizeof(int));
return 0;
}