Posts

Showing posts from February, 2017

How would you read in a string of unknown length without risking buffer overflow

How would you read in a string of unknown length without risking buffer overflow #include <stdio.h> #include <stdlib.h> char * inputString ( FILE * fp , size_t size ){ //The size is extended by the input with the value of the provisional char * str ; int ch ; size_t len = 0 ; str = realloc ( NULL , sizeof ( char )* size ); //size is start size if (! str ) return str ; while ( EOF !=( ch = fgetc ( fp )) && ch != '\n' ){ str [ len ++]= ch ; if ( len == size ){ str = realloc ( str , sizeof ( char )*( size += 16 )); if (! str ) return str ; } } str [ len ++]= '\0' ; return realloc ( str , sizeof ( char )* len ); } int main ( void ){ char * m ; printf ( "input string : " ); m = inputString ( stdin , 10 ); printf ( "%s\n" , m ); free ( m ); return 0 ; }

A program to check if a binary tree is BST or not

Image
A binary search tree (BST) is a node based binary tree data structure which has the following properties. • The left subtree of a node contains only nodes with keys less than the node’s key. • The right subtree of a node contains only nodes with keys greater than the node’s key. • Both the left and right subtrees must also be binary search trees. From the above properties it naturally follows that: • Each node (item in the tree) has a distinct key. METHOD 1 (Simple but Wrong) Following is a simple program. For each node, check if left node of it is smaller than the node and right node of it is greater than the node. int isBST(struct node* node) { if (node == NULL) return 1; /* false if left is > than node */ if (node->left != NULL && node->left->data > node->data) return 0; /* false if right is < than node */ if (node->right != NULL && node->right->data < node->data) return 0;

Dynamic memory allocation

Dynamic memory allocation with new and delete The need for dynamic memory allocation C++ supports three basic types of memory allocation, of which you’ve already seen two. Static memory allocation  happens for static and global variables. Memory for these types of variables is allocated once when your program is run and persists throughout the life of your program. Automatic memory allocation  happens for function parameters and local variables. Memory for these types of variables is allocated when the relevant block is entered, and freed when the block is exited, as many times as necessary. Dynamic memory allocation  is the topic of this article. Both static and automatic allocation have two things in common: The size of the variable / array must be known at compile time. Memory allocation and deallocation happens automatically (when the variable is instantiated / destroyed). Most of the time, this is just fine. However, you will come across situations where on