Thursday, 28 December 2017

what is the difference between memory leak & memory wastage

what is the difference between memory leak & memory wastage


Memory leak

   Programmers create a memory in heap and forget to delete it and don't have any variable to track the memory, so that in future if we want to delete the memory in code that is not possible this is call memory leak.

Memory wastage:

    User created the memory and forget to delete it but he has the variable to track the memory then that is called the wastage of memory not an leak.

Example:

#include <stdio.h>
#include <stdlib.h>
char *buffer = NULL;
void fun()
{
    char *ptr = NULL;
    if(buffer == NULL) {
        ptr = (char *) malloc(128);
        buffer = ptr;
    }
    else {
        ptr = buffer;
    }
    printf("Vel Enter the details: ");
    scanf("%s", ptr);
    printf("Vel Entered value is = (%s) \n\n", ptr);
    //  we don't need the global variable to track for this program, so we can free this here or we can use local variable instead of heap memory.
    return; /* Return without freeing ptr*/
}

int  main()
{
    fun();
    while(1) {
        /* Added this while to make sure that the process is still running but we could not
           free the memory once come out from the fun().  */
        sleep(1);
    }
    // here or some where  in the program we need to free the buffer if it is not used,
    // we are not using the buffer  anymore and still tracking the memory using variable then that is not an leak, that is an wastage of memory, programmer not handled the memory efficiently.
    return 0;
}


What is Memory Leak? How can we avoid?


What is Memory Leak? How can we avoid?

Memory leak occurs when programmers create a memory in heap and forget to delete it.
If we dont have any variable to track that memory.

Example : Memory Leak:


#include <stdio.h>
#include <stdlib.h>

void fun()
{
    char *ptr = (char *) malloc(128);
    printf("Vel Enter the details: ");
    scanf("%s", ptr);
    printf("Vel Entered value is = (%s) \n\n", ptr);
    //  we dont have any variable to track that memory
    return; /* Return without freeing ptr*/
}

int  main()
{
    fun();
    while(1) {
        /* Added this while to make sure that the process is still running but we forget to
           free the memory once come out from the fun() and dont have variable to track that memroy.  */
        sleep(1);
    }

    return 0;
}

How to avoid memory leak:

       Memory allocated on heap should always be freed(using free() call) when no longer needed.

Example :

#include <stdio.h>
#include <stdlib.h>

void fun()
{
    char *ptr = (char *) malloc(128);
    printf("Vel Enter the details: ");
    scanf("%s", ptr);
    printf("Vel Entered value is = (%s) \n\n", ptr);

    free(ptr);
    return;
}

int  main()
{
    fun();
    while(1) {
        /* Added this while to make sure that the process is still running but we forget to
           free the memory once come out from the fun() and dont have variable to track that memroy.  */
        sleep(1);
    }

    return 0;
}



Tuesday, 19 December 2017

perror & strerror, convert the perror number into an string value


What is perror ?

The C library function void perror(const char *str) prints a descriptive error message to stderr.
First the string str is printed, followed by a colon then a space.
Str = User string.

what is strerror ?

The strerror() function returns a pointer to a string that describes the error code passed in the argument errnum.
Possibly using the LC_MESSAGES part of the current locale to select the appropriate language. (For example, if errnum is EINVAL, the returned description will "Invalid argument".)
This string must not be modified by the application, but may be modified by a subsequent call to strerror(). No library function, including perror(3), will modify this string.

Return value:

The strerror() and the GNU-specific strerror_r() functions return the appropriate error description string, or an "Unknown error nnn" message if the error number is unknown.

Example:


#include <stdio.h>
#include <errno.h>
#include <string.h>
#define BUF_64              64
int main()
{
    FILE   *fp = NULL;
    char   strerr_buf[BUF_64] = {'\0'};
    int    ret = 0;
    /* first rename if there is any file */
    rename("file.txt", "newfile.txt");
    /* now let's try to open same file */
    fp = fopen("file.txt", "r");
    if (fp == NULL) {
        perror("Error: ");
        ret = strerror_r(errno, strerr_buf, sizeof(strerr_buf));
        if (ret) {
            printf("Failed to convert errno to string ret <%d> \n", ret);
        }
        printf("velraj errno <%d> value (%s) value using _r <%s> \n", errno, strerror(errno), strerr_buf);
        return(-1);
    }
    fclose(fp);
    printf("velraj errno = 2  value (%s)\n",  strerror(2));
    return(0);
}

Output:

Error: : No such file or directory
velraj errno <2> value (No such file or directory) value using _r <No such file or directory>



Monday, 18 December 2017

Unix / Linux commands

The list of Unix/ Linux commands:

To list the file details:

          file -L /usr/lib/libpcap.so.1

Display all folders with used size:

          du -sh *

To know the Ubuntu version(Eg: 14.0):

          lsb_release -a

Convert Linux txt file into windows format:
          perl -p -e 's/\n/\r\n/' < test > dosfile3.txt

Empty the contents of a file:
          cp /dev/null <file Name to empty>


What is use of %n in printf() ?


What is use of %n in printf() ?

     In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n.


Example:
#include <stdio.h>
int main(int argc, char *argv[])
{
    int c;

    printf("velraj total 16 %n won't count after n. \n", &c); // upto n the word length is 16, this value will be saved in c variable
    printf("%d\n", c);
    return 0;
}

Output:
----- snip ---------
velraj total 16  won't count after n.
16
----- snip ---------

Friday, 15 December 2017

Days to Learn Advance C language, In debth C questions and answers




Day 1:


  1. Compilation :
                Find the compilation steps from .c format to executable format.
                Collect the files which was generated in each steps
                Analysis the file and understand the purpose of each file.


Day 2:


  1. What are all storage class is available in c,  the scope (visibility) and life-time of variables and/or functions within a C Program.
  2. Difference between static function & normal function.  With example programs.


Day 3:


  1. Memory Layout of C Programs ?
    1. Check the size of text, data, and bss segments of below programs.
      1. Check the following simple C program
                                                           #include <stdio.h>
                                               int main(void)
                                                          {
                                                                return 0;
                                                           }


    1.   Let us add one global variable in program, now check the size of bss (highlighted in red color)
                                                         #include <stdio.h>
                                              int global; /* Uninitialized variable stored in bss*/
                                              int main(void)
                                                         {
                                                             return 0;
                                                         }


  1. Let us add one static variable which is also stored in bss.
                                                        #include <stdio.h>
                                             int global; /* Uninitialized variable stored in bss*/
                                             int main(void)
                                                       {
                                                            static int i; /* Uninitialized static variable stored in bss */
                                                            return 0;
                                                        }

  1. Let us initialize the static variable which will then be stored in Data Segment (DS)
                                            #include <stdio.h>
                                            int global; /* Uninitialized variable stored in bss*/
                                            int main(void)
                                                      {
                                                           static int i = 100; /* Initialized static variable stored in DS*/
                                                           return 0;
                                                       }

  1.  Let us initialize the global variable which will then be stored in Data Segment (DS)
                                                       #include <stdio.h>
                                            int global = 10; /* initialized global variable stored in DS*/
                                            int main(void)
                                                       {
                                                           static int i = 100; /* Initialized static variable stored in DS*/
                                                           return 0;
                                                       }

Day 4:

  1. Read below to understand the heap memory:
    1. What is heap memory?
    2. Difference between malloc(), calloc() & realloc()
    3. What is Memory Leak? How can we avoid?
      1. Answer: Memory Leak
    4. what is the difference between memory leak & memory wastage
      1. Answer: Memroy Leak vs Memory wastage
    5. Why need to use free() ?
    6. what is heap corruption in c ?

Friday, 8 December 2017

Understand the 2nd Array size, access &




#include <stdio.h>


int main()
{
    int arr[4][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};


        printf("Vel arr[0] = %p (arr+1) = %p *(arr+1) = %p \n", arr[0], (arr +1), *(arr+1));



        // Below 2 contain the following same warning
/*array_2d_understand.c:12:9: warning: format ‘%p’ expects argument of type ‘void *’, but argument 4 has type ‘int’ [-Wformat=]
  printf("Vel arr[1] = %p arr[1] = %p arr[1][1] = %p \n", arr[1], arr[1], arr[1][1]); */ 
       printf("Vel arr[1] = %p arr[1] = %p arr[1][1] = %p \n", arr[1], arr[1], arr[1][1]);

        printf("Vel *((arr +1)+1) = %p *(arr+2) = %p *(*(arr +1) +1) = %p arr[1][1] = %p \n", *((arr +1)+1), *(arr+2), *(*(arr +1) +1), arr[1][1]);
        printf("Vel (*(arr +1) +1) = %p &arr[1][1] = %p \n", (*(arr +1) +1), &arr[1][1]);


        printf("\n\n\tarr[4][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}} \n");
        printf(" \n\t Understand : (arr+1) != *(arr+1) The address of this 2 output will be same \n\t"
               "but they are not equal because arr+1 is a 2nd  array arr is incremented by 1 Hence further\n\t"
               " increment is incremented by 3 but *(arr+1) is 2nd array is now converted to 1D arry because of \n\t"
               "* hence further increment is only sizeof int. \n");
}







Output:
Vel arr[0] = 0xbfcafb6c (arr+1) = 0xbfcafb78 *(arr+1) = 0xbfcafb78
Vel arr[1] = 0xbfcafb78 arr[1] = 0xbfcafb78 arr[1][1] = 0x5
Vel *((arr +1)+1) = 0xbfcafb84 *(arr+2) = 0xbfcafb84 *(*(arr +1) +1) = 0x5 arr[1][1] = 0x5
Vel (*(arr +1) +1) = 0xbfcafb7c &arr[1][1] = 0xbfcafb7c


    arr[4][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}}

     Understand : (arr+1) != *(arr+1) The address of this 2 output will be same
    but they are not equal because arr+1 is a 2nd  array arr is incremented by 1 Hence further
     increment is incremented by 3 but *(arr+1) is 2nd array is now converted to 1D arry because of
    * hence further increment is only sizeof int.

~                             

Understand the 2d Array size

array_2d_size.c

This program is used to understand the 2d array size


#include <stdio.h>


int array_arg_size(int ptrarr[][3])
{
        printf("Vel array_arg_size size of ptrarr[][3] = %d \n", sizeof(ptrarr));





       // Here user will get the below warning
        /*warning as : warning: ‘sizeof’ on array function parameter ‘ptrarr’ will return size of ‘int (*)[3]’ [-Wsizeof-array-argument] */

}

int main()
{
    int arr[4][3] = { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};
    int (*ptr)[3];
//     int ptrarr[][4]; throws error as " error: array size missing in ‘ptrarr’"
  
        printf("Vel sizeof arr[4][3] = %d , (*ptr)[3]= %d,  & NULL = %d \n", sizeof(arr), sizeof(ptr),  sizeof(NULL));

        array_arg_size(arr);
        return 0;
}

/* Output :
       Vel sizeof arr[4][3] = 48 , (*ptr)[3]= 4,  & NULL = 4
       Vel array_arg_size size of ptrarr[][3] = 4  */

List of C questions and answers in all the modules