Posts

Showing posts from April, 2015

Security Concepts

Image
Encryption:   It is the process of converting message (referred as plain text in cryptography) into another form (referred to as cipher text) in such a way that only authorized persons can read or understand it.So, it is nothing but converting plain text to cipher text .This is done by some encryption algorithms .And decryption is the reverse operation,takes cipher text and converts back to the plain text. The input to the encryption algorithm is the key.The key can be anything,it can be a simple word,number, or some series of random letters. Symmetric Key Algorithms:     In symmetric key algorithm single key is used for both performing encryption and decryption.So,the other node that wants to communicate should have this key.For this operation there are key exchange protocols. Eg: RC4,3DES etc Asymmetric Key Algorithms:      In asymmetric key algorithms,there are two keys:public key and private key.Public key is shared and private key is secret.In order to encrypt we us

What is a void pointer in C programming language?

Definition:       A pointer that can hold the address of any data type.It can be pointed to any data type by typecasting.It is declared with the void keyword placed in the data type. Example: void *ptr; int main() { int a=3; char ch='c'; void *ptr=&a;//pointing to an int ptr = ch;//pointing to an char return 0; } Important Points: 1. void pointer cannot be dereferenced.If you try to do it you will get a compile time error.For example: int main() { int a; void *ptr= &a; printf("value:%d\n",*a); return 0; } 2.You cannot perform pointer arithmetic operation on void pointer .For example int main() { int a; void *ptr = &a; ptr++; return 0; }

Write your own sizeof function in C

This is the most common interview asked , i have seen qualcomm asking this question in their first round. sizeof is used to calculate the size of any datatype.It is implemented by compilers. We will write a macro that performs the same functionality as by the sizeof implemented by compiler. #include #define SIZEOF(X) (int)(((typeof(X)*)0)+1) int main(int argc,char *argv[]) { int a; char b; float c; double d; int *e; int f[10]; printf("size of a is %d\n",SIZEOF(a)); printf("size of b is %d\n",SIZEOF(b)); printf("size of c is %d\n",SIZEOF(c)); printf("size of d is %d\n",SIZEOF(d)); printf("size of e is %d\n",SIZEOF(e)); printf("size of f is %d\n",SIZEOF(f)); printf("size of char is %d\n",SIZEOF(char)); }

Allocating two dimensional array dynamically using C

One of the most common interview questions asked in interview is to dynamically allocate a 2-D array, The following code is dynamically allocating  a 2-D array #include int main() { int **pointer; pointer = (int **) malloc(rows *sizeof(int *)); if (pointer == NULL) { perror("Failed to allocate\n"); return -1; }else { int i; for (i = 0; i < rows; i++) { pointer[i] = (int *)malloc(columns*sizeof(int)); if (pointer[i] == NULL) { perror("Failed to allocate\n"); return -1; } } } Now you can use pointer in similar syntax of two dimensional array. Eg: pointer[i][j];

Accept a string of multiple words in C using scanf

Today we will see how we can store a string in C. Suppose if we have try to copy by using scanf: char array[24]; scanf("%s",array); This will copy only the first word of the string in the array We have to use scanf with circumflex(^) char array[24]; scanf("%[^\n]",array); The following statement will copy the string passed into the buffer until it received a new line character.

C program to reverse the string word by word

The following C program will reverse the string word by word Example: If the input is : Have a nice day Output will be:day nice a Have #include #include void swap(char *string, int length) { int i; char ch; for (i = 0; i < length/2; i++) { ch = string[length-i-1]; string[length-1-i]=string[i]; string[i]=ch; } } char *reverse(char *string) { int length = strlen(string); char ch; int i, prev_index; /* * The following for loop for swap the character to character */ for ( i = 0 ; i < length/2; i++) { ch = string[length-1-i]; string[length-1-i] = string[i]; string[i] = ch; } /* * Next for loop we have to swap word by word */ i = 0; while (string[i] !='\0') { prev_index = i; while (string[i] != ' ' && string[i] != '\0') i++; swap(string+prev_index,i - prev_index); if(string[i] == ' ') i++; } return string; } int main(int argc, char *argv[]) { char str[100]; printf("Ent

What is Cache?Cache hit and Cache miss

What is Cache? --> It is a block of memory for temporary storage of data which will be used frequently. --> Accessing data from cache will be faster when compared to accessing it from a main memory(RAM) ---> Caches are type of SRAM.SRAM are costlier than DRAM because it requires 6 transistors to store one bit whereas DRAM are cheaper as it requires only one transistor and capacitor, but the disadvantage with DRAM is that it has to be refreshed each time. --->Need for cache's arised because the speed of the processor is more compared to the speed of the main memory.So in order to match the speed, cache is kept between processor and RAM --->If a processor has to perform an I/O(read/write) operation on any memory location,it will check whether the data of that memory location is present in the memory or not.If it is present it will directly perform I/O operation on that memory.This is called cache hit .If the data is not present in the cache.It is called cac

Valgrind Tutorial Part 6 -- Callgrind

As we already valgrind is basically a wrapper around a lot of tools.In the previous posts, we were using the most popular valgrind tool known as memcheck,today we will be using another tool known as callgrind. Before knowing about callgrind we have to know about profiling in programming... What is profiling? Profiling is a form of dynamic program analysis,that measures things such as  1.Time complexity  2. Space complexity  3. How many times a particular function is called.  4. Time taken to execute a particular function. Basically , we use it to find where our program is taking more amount of time and try to optimize it. So there are many tools which performs profiling operation such as gprof..valgrind also has a tool i.e.,callgrind..So, we now know that cachegrind is  a profiling tool. So,in order to use this tool,you have to specify --tool=cachegrind as an argument to the valgrind else the default tool memcheck will be considered. So, in order to perform profili

GIT tutorial Part1

Suppose you are have to write a C code.You will start with writing the code with minimum features then you start adding features one by one .After adding each feature you will check whether your application is working fine.If your application is working fine then no issue,you will continue with the next feature.Suppose your application was working fine ,when you added a feature, so u started adding a new feature,But after adding some of the code of the latest feature,you found that application is misbehaving,now you dont know whether the issue is due to the latest feature or some bug is still present in the previous feature you added,In this scenario versioning tools are most useful.One of the best tools out of it is git.So we will start a tutorial on git ,where we will learning most commonly used commands present in the git. First step is to install git. Go to your command line( ctrl+alt+t ) and type: sudo apt-get install git It will first download and will install the git in yo

How function pointer written in C is mapped to assembly

We will take the simplest microcontroller to understand this because we will be having less instructions present in it. We here are taking atmega8 microcontroller instruction set to understand this. Suppose we are having the following C code in which we will be using a function pointer to call a C function. void (*ptr)(void); void fn(void){ //suppose this is present at the address 0x34 in program memory asm("nop"); } int main(void) { ptr = fn; ptr(); } The first line ptr=fn is mapped to the following assembly instructions ldi R24,$34 ;lower 8 bits addrress ldi R25,$00 ;higher 8 bits address sts $0063,R25 ;storing higher bits first sts $0062,R24 ;storing lower bits then The call ptr() is mapped to the following assembly instructions lds R30,$0062 ;loading the lower bits lds R31,$0063 ;loading the higher bits icall ; icall will make the PC points to the address present in the Z register

Valgrind Tutorial - Part 5

Errors Occur Due to Invalid System Call Parameter can be found using valgrind int main(void) { int *ptr; ptr = malloc(10); read(0, ptr, 100); /* Error: unaddressable bytes */ free(ptr); return 0; } You can see the following code we allocated 10 bytes and we are trying to read 100 bytes from stdin(standard input). Run the following commands gcc -o app app.c -g valgrind --tool=memcheck --leak-check=yes ./app

Valgrind Tutorial -Part 4

Invalid Free:Whenever your trying to free a memory location twice , the application crashes.Using valgrind , we can also know whether our code is doing invalid free or not. int main(void) { int *ptr, i; ptr = malloc(10*sizeof(int)); for(i = 0;i < 10;i++) ptr[i] = i; free(ptr); free(ptr); /* Error: ptr has already been freed */ return 0; } In the following program we have allocated a pointer and allocated 10 integer variables and in the next step we are initializing each of the variable. Next we will free the heap memory allocated. But in the next step we are trying to free the already freed memory which is wrong. So with valgrind you can check this error also. compile the application using gcc   gcc -o app app.c -g Run the valgrind tool valgrind --tool=memcheck --leak-check=yes  ./app O/P: ==31277== Memcheck, a memory error detector ==31277== Copyright (C) 2002-2011, and GNU GPL'd, by Julian

Valgrind Tutorial - Part 3

Valgrind also throws an error whenever we are trying to read a uninitialized memory, for example take a look for the following C code int main(void){ int i; int arr[10]; for (i = 0; i < 9; i++) arr[i] = i; for (i = 0; i < 10; i++){ printf("%d ", arr[i]); } printf("\n"); return 0; } In the example, we have declared an integer array of size 10 . In the next step we are initializing each of the variable of the array with a integer value except the last member. So whenever we are accessing the last member without actually initializing we dont know what actual value is present,it is due to the scope of the array,as it is local variable the default will be garbage. Valgrind throws error whenever you give the executable to it.  Compile the application with -g option gcc -o app app.c -g Use valgrind command to find out whether there is any error in the code. valgrind --tool=memcheck --leak-check=yes ./app O/p of valgrind: ==37

Valgrind Tutorial - Part 2

By using valgrind we can also find out whether we are performing read/write operation on an array beyond its limit(size) Take a look at this sample code int main(void) { int i; int *a = malloc(sizeof(int) * 12); if (!a) return -1; /*malloc operation has failed*/ for (i = 0; i < 15; i++){ a[i] = i; } free(a); return 0; } You can see in the following code that iam allocating a integer array of size 12 by using malloc but i am trying to access beyond the size of array that is array[12],array[13] and array[14] which is wrong By using valgrind memcheck tool you can find out the error So first compile the code by passing -g to gcc to include debugging operation   gcc -o app app.c -g  Now run the valgrind tool using the following command valgrind --tool=memcheck --leak-check=yes  ./app ==29768== Memcheck, a memory error detector ==29768== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al. ==29768== Using

linux macro in C

int main(void) { int linux = 5; printf("%d",linux); return 0; } When u compile this application using gcc in linux, you will get compilation error, this is because linux is a macro which is defined to 1 You can look this by stopping at the preprocessing stage gcc -E test.c will stop this at the preprocessing stage. int main(void) { int 1 = 5; printf("%d",1); return 0; } You can see the linux is expanded to 1 in the preprocessing stage and hence the error.

C program to draw india map

main() { int a,b,c; int count = 1; for (b=c=10;a="- FIGURE?, UMKC,XYZHello Folks,\ TFy!QJu ROo TNn(ROo)SLq SLq ULo+\ UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^\ NBELPeHBFHT}TnALVlBLOFAkHFOuFETp\ HCStHAUFAgcEAelclcn^r^r\\tZvYxXy\ T|S~Pn SPm SOn TNn ULo0ULo#ULo-W\ Hq!WFs XDt!" [b+++21]; ) for(; a-- > 64 ; ) putchar ( ++c=='Z' ? c = c/ 9:33^b&1); return 0; }

Valgrind Tutorial - Part 1

Today we will be starting a series on Valgrind.We will writing various programs and use valgrind to detect the possible errors that can occur. About Valgrind: 1. Debugging Tool 2.It is a wrapper around various tools for debugging and profiling.Best tool out of these is MemCheck that is used to find out memory leaks etc. In order to use valgrind you have to include debugging information that is you should compile the application with -g option if you are using gcc . We will use the  Memcheck tool to find out memory leak C-Program int main(void) { char *ptr; /**Here we are allocating 19 bytes of memory using malloc **/ ptr = (char *)malloc(19); /**Here we are again allocating 12 bytes of memory using *malloc to the same pointer **/ ptr = (char *) malloc(12); free(ptr); /**Allocating 16 bytes using malloc**/ ptr = (char *) malloc(16); return 0; } Now when we compile the application using gcc   gcc -o app app.c -g It will generate the bi