Wednesday 24 July 2013

How to view a lib ,exe or dll in windows

We can use dumpbin to view the storage of variables and functions of all these three types of  files lib ,exe and dll.nm is used to show the all function of the dll and lib .nm is not applicable for .exe files.We can use this command in following manner on command prompt:

1)Go to the folder where the the file is available.
2)nm filename.lib



Sunday 21 July 2013

How to use Cmake in windows

firstly run the cmake-gui
a)create a build directory in the src directory
b)put the path to src in first tab
c)put the path  of build directory in build tab
d)click configure
e)click configure again each time you make any change
f)Then click genrerate

Here is the snapshot of the c-make gui:-


Friday 14 June 2013

Different compression techniques

LZ77:-LZ77 algorithms achieve compression by replacing repeated occurrences of data with references to a single copy of that data existing earlier in the input (uncompressed) data stream. A match is encoded by a pair of numbers called a length-distance pair, which is equivalent to the statement "each of the next length characters is equal to the characters exactly distance characters behind it in the uncompressed stream". (The "distance" is sometimes called the "offset" instead.)

LZ78:-LZ78 algorithms achieve compression by replacing repeated occurrences of data with references to a dictionary that is built based on the input data stream. Each dictionary entry is of the form dictionary[...] = {index, character}, where index is the index to a previous dictionary entry, and character is appended to the string represented by dictionary[index]. For example, "abc" would be stored (in reverse order) as follows: dictionary[k] = {j, 'c'}, dictionary[j] = {i, 'b'}, dictionary[i] = {0, 'a'}, where an index of 0 specifies the first character of a string. The algorithm initializes last matching index = 0 and next available index = 1. For each character of the input stream, the dictionary is searched for a match: {last matching index, character}. If a match is found, then last matching index is set to the index of the matching entry, and nothing is output. If a match is not found, then a new dictionary entry is created: dictionary[next available index] = {last matching index, character}, and the algorithm outputs last matching index, followed by character, then resets last matching index = 0 and increments next available index. Once the dictionary is full, no more entries are added. When the end of the input stream is reached, the algorithm outputs last matching index. Note that strings are stored in the dictionary in reverse order, which an LZ78 decoder will have to deal with.

LZW:-Lempel–Ziv–Welch (LZW) is a universal lossless data compression algorithm created by Abraham Lempel, Jacob Ziv, and Terry Welch. It was published by Welch in 1984 as an improved implementation of the LZ78.LZW starts out with a dictionary of 256 characters (in the case of 8 bits) and uses those as the "standard" character set. It then reads data 8 bits at a time (e.g., 't', 'r', etc.) and encodes the data as the number that represents its index in the dictionary. Everytime it comes across a new substring (say, "tr"), it adds it to the dictionary; everytime it comes across a substring it has already seen, it just reads in a new character and concatenates it with the current string to get a new substring. The next time LZW revisits a substring, it will be encoded using a single number. Usually a maximum number of entries (say, 4096) is defined for the dictionary, so that the process doesn't run away with memory. Thus, the codes which are taking place of the substrings in this example are 12 bits long (2^12 = 4096). It is necessary for the codes to be longer in bits than the characters (12 vs. 8 bits), but since many frequently occuring substrings will be replaced by a single code, in the long haul, compression is achieved.

LZSS:-Lempel–Ziv–Storer–Szymanski (LZSS) is a lossless data compression algorithm, a derivative of LZ77, that was created in 1982 by James Storer and Thomas Szymanski. LZSS is a dictionary encoding technique. It attempts to replace a string of symbols with a reference to a dictionary location of the same string.
The main difference between LZ77 and LZSS is that in LZ77 the dictionary reference could actually be longer than the string it was replacing. In LZSS, such references are omitted if the length is less than the "break even" point. Furthermore, LZSS uses one-bit flags to indicate whether the next chunk of data is a literal (byte) or a reference to an offset/length pair.

LZMA:-LZMA is default and general compression method of 7z format. The Lempel–Ziv–Markov chain algorithm (LZMA) is an algorithm used to perform lossless data compression.LZMA compression algorithm is very suitable for embedded applications. LZMA is released under the terms of the GNU LGPL. LZMA is also available under a proprietary license for those who can not use the GNU LGPL in their code. If you want to use LZMA code, you can ask consultations, custom code programming and required developer licenses from page for support: Send message to LZMA developer. Check also information about LZMA SDK.

x264:-x264 is the world’s most popular H.264 video encoder, and is highly optimized with hand written vectorized assembly code.x264 is a free software library for encoding video streams into the H.264/MPEG-4 AVC format. It is released under the terms of the GNU General Public License.

ffmbc:-What we can do with FFmbc:

Import your files in Final Cut Pro, AVID Media Composer, Adobe Premiere
Create XDCAM HD422 files in .mov or .mxf
Create XDCAM IMX/D-10 files in .mov or .mxf
Create AVID DNxHD files in .mov
Create DVCPROHD files in .mov or .mxf
Create ProRes 422 or 4444 files in .mov
Convert V210 Files
Convert HD YUV BT709 to SD BT601 and vice versa
Convert AVCIntra 50 and 100
Convert MPEG-TS files with SMPTE 302M audio
Convert AVCHD files correctly
Convert ProRes 422 and 4444 files
Rewrap IMX/D-10, AVCHD, DVCPROHD to Quicktime for editing in Final Cut Pro
Burn ASS or SRT subtitles files in videos
Merge and split your audio tracks
Create Quicktime files containing time code tracks
Color conversion from HD to SD
Read timecode tracks from MXF, Quicktime
Creating audio files (mp3 and m4a) with cover art
Keep or add covert art when converting your audio files
Faststart MP4 for streaming (replace header in front) automatically

Yasm:-In computing, Yasm is an assembler, a full rewrite of Netwide Assembler (NASM). Yasm can generally be used interchangeably with NASM and supports the x86 and x86-64 architectures. It is licensed under a revision of the BSD licenses. As of 2011 it was developed by Peter Johnson and Michael Urman.It can assemble input with both Intel and AT&T (as) syntax;Library interface for compiler developers.

libmp3lame:-"libmp3lame-3.97" is a encoder that enables you to save/encode the file into Mp3 format. You should this download it so as to export a file to Mp3 which is edited in Audacity.


Tuesday 11 June 2013

Preprocessor Operators/Directives/Macros/Pragmas in c

Here are some preprocessor operators/directives/macros in  c

1) PREPROCESSOR OPERATORS

Stringizing operator (#):-Causes the corresponding actual argument to be enclosed in double quotation marks.

charizing Operator (#@):-Causes the corresponding argument to be enclosed in single quotation marks and to be treated as a character (Microsoft Specific).

Token Pasting Operator (##):-Allows tokens used as actual arguments to be concatenated to form other tokens.

DEFINED operator:-Simplifies the writing of compound expressions in certain macro directives.



2) PREPROCESSOR DIRECTIVES

#                 (NULL DIRECTIVE)
----------------------------------------------------------------------------------------------------------------------------------
#include

#if
#else
#define

Example:-

#include<stdio.h>
#include<conio.h>
#define DLEVEL 1

#if DLEVEL > 5
    #define SIGNAL  1 //this is disable
   
#else
    #define SIGNAL  0  //////////this is enable
  
#endif

void main ()
{

printf("Hi\n");
_getch();
}

------------------------------------------------------------------------------------------------------------
#endif
#elif

Example:-

#include<stdio.h>
#include<conio.h>
#define DLEVEL 1

#if DLEVEL == 0
    #define STACK 0
#elif DLEVEL == 1
    #define STACK 100 //////////only this is enable ,rest of all are disable
#elif DLEVEL > 5
    #define STACK 300
#else
    #define STACK 200
#endif

void main ()
{

printf("Hi\n");
_getch();
}

------------------------------------------------------------------------------------------------------------

#ifdef
#ifndef
#undef

Example:-

#include<stdio.h>
#include<conio.h>
#define DLEVEL 1
#undef DLEVEL ////undefine the DLEVEL


#ifdef DLEVEL
#define SIGNAL //////this is disable
#endif
#ifndef DLEVEL
#define final     //////////this is enable
#endif
void main ()
{

printf("Hi\n");
_getch();
}


-----------------------------------------------------------------------------------------------------------
#line:-The #line directive tells the preprocessor to change the compiler's internally stored line number and filename to a given line number and filename.

#line digit-sequence ["filename"]
#using:-Imports metadata into a program compiled with /clr.

#using file [as_friend]

#import:-Used to incorporate information from a type library. The content of the type library is converted into C++ classes, mostly describing the COM interfaces.

#error:-Error directives produce compiler-time error messages.

Example:-


#include<stdio.h>
#include<conio.h>
#define DLEVEL 1

#undef DLEVEL

#ifndef DLEVEL
#error DLEVEL is not defined
#endif

void main ()
{

printf("Hi\n");
_getch();
}

When we compile this program apart from an intellisense error it displays a compilation error which shows following message:-

error C1189: #error :  DLEVEL is not defined

3) PREDEFINED MACROS

__DATE__:-The compilation date of the current source file. The date is a string literal of the form Mmm dd yyyy. The month name Mmm is the same as for dates generated by the library function asctime declared in TIME.H.

__FILE__:-It returns the name of the current source file.

__LINE__:-It returns the line number in the current source file .

Here is an use of __FILE__ and __LINE__ where we want to know in which file the error occurs and at which line so we use the following syntax.


#define CudaCheckError(cudaStatus) if (cudaStatus != cudaSuccess) {printf("\n%s\t%s\t%d", cudaGetErrorString(cudaGetLastError()),__FILE__,__LINE__);_getch();}

It returns the cuda error was which type ,in which file and in that file at which line.


__TIME__:-The most recent compilation time of the current source file. The time is a string literal of the form hh:mm:ss.

__TIMESTAMP__:-The date and time of the last modification of the current source file, expressed as a string literal in the form Ddd Mmm Date hh:mm:ss yyyy, where Ddd is the abbreviated day of the week and Date is an integer from 1 to 31.


_FUNCTION_:-Valid only within a function and returns the undecorated name of the enclosing function (as a string). 

_cplusplus:-Defined for C++ programs only.

_WIN32:-Defined for applications for Win32 and Win64. Always defined.

_WIN64:-Defined for applications for Win64.

_OPENMP:-Defined when compiling with /openmp, returns an integer representing the date of the OpenMP specification implemented by Visual C++.
// _OPENMP_dir.cpp
// compile with: /openmp 
#include <stdio.h> 
int main() {
   printf("%d\n", _OPENMP);
}


_DEBUG:-Defined when compiling with /LDd, /MDd, and /MTd.

_DLL:-Defined when /MD or /MDd (Multithread DLL) is specified.

_MT:-Defined when /MD or /MDd (Multithreaded DLL) or /MT or /MTd (Multithreaded) is specified.

4) PRAGMA DIRECTIVES

#pragma omp:-It takes one or more OpenMP directives, along with any optional directive clauses.

#pragma omp directive

#pragma pack:-Specifies packing alignment for structure, union, and class members.

#pragma pack( [ show ] | [ push | pop ] [, identifier ] , n  )
-----------------------------------------------------------------------------------------------------------------------------#pragma region:-lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.

#pragma endregion:-#pragma endregion marks the end of a #pragma region block.

A #region block must be terminated with #pragma endregion.


#pragma region name
#pragma endregion comment

Parameters:-
comment(optional)
A comment that will display in the code editor.
name(optional)
The name of the region. This name will display in the code editor.

------------------------------------------------------------------------------------------------------------------------------

#pragma auto_inline:-Excludes any functions defined within the range where off is specified from being considered as candidates for automatic inline expansion.

#pragma auto_inline( [{on | off}] )

The auto_inline pragma is placed before and immediately after a function defintion.It can not be declare in function definition.The pragma takes effect at the first function defintion after the pragma is seen.

#pragma once:-
Specifies that the file will be included (opened) only once by the compiler when compiling a source code file.This can reduce build times as the compiler will not open and read the file after the first #include of the module.
-- 

Creating XML file in C

We can create a xml file using C language.It is possible to enter values into a xml file through program.We can use fprintf to write into a file.Here is the program for this:-

#include<stdio.h>
#include<conio.h>

#define numcomp 20

void main()
{
int i=0;
    FILE* XMLFile = fopen("output.xml","wb");

fprintf(XMLFile,"<zones count=\"%d\">\n",numcomp);
for(i=1;i<=numcomp;i++)
    {
fprintf(XMLFile,"<zone index=\"%d\">\n",i);
fprintf(XMLFile,"%s","</zone>\n");
    }
fprintf(XMLFile,"</zones>\n",numcomp);
fclose(XMLFile);
printf("file is created");
_getch();
}

Output XML File :-


dll | lib | VS

The .lib in this context is not a static library. It is just a library which loads the dll.

------------------------------
VS project should know the name of .lib and location of .lib
linker ->input->dependencies (.lib)
general -> additional library directory  (directory of .lib)

If .lib is in the same directory as .exe , there is no need to mention directory of lib in VS.

-----------------------------
The dll can be placed in system32 directory.
The dll can be placed in any directory, but that directory should be added in system path.
The dll can be in the same directory as the exe.
---------------------------------

1) .exe and .lib is in same directory and .dll is in 
   a) system32
   b) any directory specified by PATH
   c) same directory as exe and lib

2) .exe is in one directory,  
    .lib is in some other directory (location specified in VS) and 
    .dll is in 
        a) system32
         b) any directory specified by PATH
         c) same directory as exe 
         d) same directory as lib

Setting the PATH environment variable

There are few steps to setting the path of environment variable which are following:-

1)Goto the control panel
2)Control panel -> system
3)System->change settings
4) Change settings -> system properties
5)System properties -> advanced
6)Advanced->  Environment variables
7)Environment variables ->New







We can see here in second image there is two type of environment variables available here .We can edit both of them or create them.Here we need to create a new user variable by clicking new in "user variables for user". Here in the third image we can see there are two text fields  "variable name" and "variable value" .In "variable name  " we assign a name for variable and in "variable path" we assign the path of the variable in system.By clicking ok the user variable is created .With same procedure we can create the system environment variables.

Wednesday 29 May 2013

difference between workstation and server

"Server" and "Workstation" are purely marketing terms, they are just approximate designations: they have absolutely no standard meaning and the company you're working with can define them as whatever they want to define them as. A computer being called a "Server" doesn't mean that it is better or higher quality an a computer called a "Workstation". In fact, you could take an identical computer and sell it as a "Workstation" to one company and a "Server" to another company and you would be entirely correct and neither company would have right to complain.

IF you buy from a large-scale vendor like Dell or HP then a "Server" will usually have higher quality components than a "Workstation". If you're buying from a small vendor or local shop than I can almost guarantee you that the quality of the components used in both are close to identical. They may offer different options on the different models, but those distinctions are for marketing reasons. If you bought a "Workstation" and a "Server" with the same motherboard you could swap any component in the two systems the two would continue to function as before.

You can build a "Server" with "Desktop" components. Internally, computer components all do exactly the same thing - if they didn't, then software would have to be recompiled for every single different model of computer.

Thursday 18 April 2013

C String functions and Numeric format

Today ,I wrote two programs one for C string functions and other one for numeric format conversions in C.First, we will discuss string functions which are used frequently in programs.Here are some important C functions:-

Here is the program for the same functions:-


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char str1[] = "amar";
char stra[] = "amar123";
char strb[] = "12334amar";
char str10[] = "my,name.is-amar";
char str2[40] ;
char str3[40];
char str4[40];
char str5[40];
char str6[40] = "singh";
char str7[40] ="hi";
char str8[40] = "bye" ;
char str9[40] ;
char str11[40];
char *ch = strchr(str6 ,'n');
char *ch1 = strrchr(str1 ,'a');
char keys[] = "1234567890";
char vowel[] ="aeiou";
int i = strcspn(stra,keys);
int j = strspn(strb,keys);

//cpoy
strcpy(str3,str1);
strcpy(str2,"hi");
strncpy(str4,str6,sizeof(str6));
strncpy(str5,str1,3);
strcat(str6,str1);
strncat(str7,str1,3);
strxfrm(str8,str1,3);

memcpy(str9,str6,sizeof(str6));
memset(str10,97,sizeof(str10));
memmove(str10+5,str10+3,10);
int k=memcmp(strb,stra,sizeof(stra));
char* ch2 = strpbrk(str6,vowel);

printf("str10 = %s\n",str10);
printf("str2 = %s\n",str2);
printf("str3 = %s\n",str3);
printf("str4 = %s\n",str4);
printf("str5 = %s\n",str5);
printf("str6 = %s\n",str6);
printf("str7 = %s\n",str7);
printf("str8 = %s\n",str8);
printf("str9 = %s\n",str9);
printf("str10 = %s\n",str10);
printf("k = %d\n",k);

printf("strlen = %d\n",strlen(str1));
printf("strcmp = %d\n",strcmp(str1,str6));
printf("strncmp = %d\n",strncmp(str7,str5,3));
printf("strcoll = %d\n",strcoll(str7,str5));
printf("ch = %u\n",ch-str6+1);
printf("ch1 = %u\n",ch1-str1+1);
printf("i = %u\n",i+1);
printf("j = %u\n",j);
printf("ch2=%c\n",*ch2);

_getch();
}


Output of the program:--


str10 = aaaaaaaaaaaaaaaa
str2 = hi
str3 = amar
str4 = singh
str5 = ama
str6 = singhamar
str7 = hiama
str8 = ama
str9 = singhamar
str10 = aaaaaaaaaaaaaaaa╠╠╠╠╠╠╠╠12334amar
k = -1
strlen = 4
strcmp = -1
strncmp = 7
strcoll = 1
ch = 3
ch1 = 3
i = 5
j = 5
ch2=i


Numeric format conversion easily converts one format of datatype to other format of datatype.It uses various 
functions which are following:-


Here is the program  for the numeric formats .Here are some functions for C99 which are not used in my program and some are not supported:-

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
int i1=323,i2=345,i3=890,i4;
unsigned long int uli;
long int li,li1,li2,li3,li4,li5;
char ch1='a',ch2=99,ch3=0;
char str1[40]="345.88";
char str2[40]="36467";
char str3[40]="654647868";
char str4[40]="32.64 16.32";
char str5[40]="32.23424";
char str6[100]="684069 35a5c7 -10101011 0xe72878 010";
char *chend;
char *chend2;
float f1 = 3263.809;
float f2 = 668.098;
float f3 = 676.8798;
i4=atoi(str2);
printf("i4 = %d\n",i4);
li = atol(str3);
uli = strtoul(str2,NULL,0);

li1 = strtol(str6,&chend,10);
li2 = strtol(chend,&chend,16);
li3 = strtol(chend,&chend,2);
li4 = strtol(chend,&chend,16);
li5 = strtol(chend,NULL,8);
printf("li1 = %ld\n",li1);
printf("li2 = %ld\n",li2);
printf("li3 = %ld\n",li3);
printf("li4 = %ld\n",li4);
printf("li5 = %ld\n",li5);

double d2 = strtod(str4,&chend);
double d3 = strtod(chend ,NULL);
printf("d2 = %lf\n",d2);
printf("d3 = %lf\n",d3);

printf("uli=%lu\n",uli);
printf("li=%ld\n",li);
double d1 = atof(str5);

printf("d1=%lf\n",d1);

_getch();
}

Output:-

i4 = 36467
li1 = 684069
li2 = 3515847
li3 = -171
li4 = 15149176
li5 = 8
d2 = 32.640000
d3 = 16.320000
uli=36467
li=654647868
d1=32.234240




  

Friday 12 April 2013

Declaration and Definition of variables and functions

The main difference declaration and definition of variables and functions is that when we declare a variable or function then there is no memory allocated for that variable and function .If we declare a variable and put some value in it along with then it is called definition .We can understand this by following examples:-

Functions:-

void some_function(void); 
//function declaration because there is no memory created for it because by default it is extern outside the function

extern void some_function(void);
//function declaration because it is declared as extern it is always be a declaration because there is no memory allocated for it either will be in function or outside the function

some_function()
{
..................//this is a definition because defintion created for it
}
============
Variables:-

int i;        
//definition because there is 4-byte memory allocated for it and some garbage value put into it.

int i=0;
//definition because there is 4-byte memory allocated for it and zero put into it.

int i=5;
//definition because there is 4-byte memory allocated for it and 5 put into it.

extern int i;
//declaration because there is no memory allocated for it.

extern int i=5;
//definition because there is 4-byte memory allocated for it and 5 put into it 

Function scopes (extern storage class) and Declaraing functions within functions

Today,I run a program related to the topic "function scopes (extern storage class)  and declaraing functions within functions".We need to create two program in the same project to observe the behaviour of the extern function .Here is the both program files:-

//Source.cpp


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void f11();
void f21()
{
printf("%s\n","f21");
}
void f71()
{
printf("%s\n","f71");
}

extern void f81();

void main()
{
f11();
f21();
        void f31();
// f31();
        void f41();
f41();

        f81();
extern void f51();
f51();
        extern void f61();
f61();
        extern void f71();
f71();
_getch();
}

void f11()
{
printf("%s\n","f11");
}
void f31()
{
printf("%s\n","f31");
}
void f61()
{
printf("%s\n","f61");
}


//source1.cpp


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

void f51()
{
printf("%s\n","f51");
}
void f41()
{
printf("%s\n","f41 test");
}
extern void f81()
{
         printf("%s\n","f81");
}


Output of the program:-


f11
f21
f41 test
f81
f51
f61
f71


Now we can see here that f11 and f21 which are declared as extern are called f31 is not called because there is only a declration in the function.if we uncomment the f31 .Then it is also called .In the same f41 ,f51 and f81 also called with extern keyword  and f71 and f21 have no need to declaration  because their defintion is above the main.If f41,f51 and f81 have declare without extern keyword then there will be no effect and they printed as well as.







Wednesday 10 April 2013

Good programming practices

Here are some important points which we need to follow during programming as good programming practices:-

1)We need to initialize each variable with zero or null while declaring it.By this we reduce the chances of occurring an error due to garbage value initialized to the variables which are not intilaized.The pointrer which is not initialized while declaration may be dangerous.

2)We need to create any project in many modules means we need to create function for each specific task.It increase the reusablity of the code.

3)Always check file pointer is null or not and exit if null in the file handling programs because it may cause more problems because we don't come to know what the problem is.


  if (ColorImageFile == NULL  ||BlackandwhiteImageFile == NULL)
  {
printf("can't open the file");
exit(1);
  }

4)In file handling program use fread and fwrite in the place of fputc and fgetc because it is more efficient .

5)Use try for that part of program where is chance of an exception and handle it after try block in catch or finally.Use __try with __finally and __leave and use try for catch and throw.

6)Use modifiers with datatypes according to need .While if we have only positive values in an array then we need to declared it as unsigned int.It also increase the range twice.

7)Always prefer dynamic memory allocation because it saves memory.

8)Always give a meaning full name to the variables and functions.It plays a very important role to understand the program by anyone else or the programmer himself.

9)Adding comments is also a very important thing which helps anybody to understand a block of code in seconds.

10)Always use the format specifier corresponding to the variable declared because minor change in format specifier does major change in output .For example if we store a negative value in a signed int and print it in %u then it gives different output.So we need to be careful in this.
 

Common programming mistakes

We  discuss here some common mistakes which we do during programming.Here are the same list of these type of mistakes:-

(1)When we passing a pointer to a function which is  a pointer for array then there is no need to do malloc again then we allocate a new memory which is pointed by that poniter.Example:-
int* f1(int* );

void main()
{
int valueforb = 10;
int *bb = (int*)malloc(size*sizeof(int));
for(long unsigned int iterator = 0 ;iterator < size;iterator++)
{
bb[iterator]= valueforb ;
valueforb+=2;
}
f1(bb);
_getch();
}
int* f1(int* b)

{
        *b = (int*)malloc(size*sizeof(int));
for(long unsigned int iterator = 0;  iterator < size ; iterator++)
{
printf("%d  ",b[iterator]);
}
return b;
}


(2)Compatibility of various datatypes and modifiers:-If we don't know which  modifier used with which datatype it causes a big trouble.So we can understand it by these link:
http://amarsinghbishen007.blogspot.in/2013/03/compatibility-of-various-data-types-and.html

(3)Unusual behaviour of signed and unsigned modifier with float:-Here is a link which describe us about this problem:-
http://amarsinghbishen007.blogspot.in/2013/03/unusual-behaviour-of-signed-and.html

(4)Right Shift of signed,unsigned char & int:-Here is a link which describe us about this problem:-
http://amarsinghbishen007.blogspot.in/2013/02/right-shift-of-signedunsigned-char-int.html

(5)using shift operator:-Here is a link which describe us about this problem:-http://amarsinghbishen007.blogspot.in/2013/01/shift-operator-signedunsigned.html

(6)We need to be very careful in giving a path for the file because if we left a \ (slash ) only then it does not give an error .We are unable to understand which type of error occurred .

Returning an array

Returning an array allocated by malloc gives an expected result.We can check it by two experiments:-

(1)By malloc in a function f() and printing it in a main
(2)By malloc in main and printing it in function f1

We use both method in a program to check if we return an array allocated by malloc gives correct result or not.Here is the program:-


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include<math.h>
#define size 50

int* f();
int* f1(int*);

void main()
{
int valueforb = 10;
int *aa=(int*)f();
int *bb = (int*)malloc(size*sizeof(int));
for(long unsigned int iterator = 0 ;iterator < size;iterator++)
{
bb[iterator]= valueforb ;
valueforb+=2;
}
f1(bb);
printf("\n");
//print aa in loop;
for(long unsigned int iterator = 0;  iterator < size ; iterator++)
{
printf("%d  ",aa[iterator]);
}
_getch();
}

int* f()
{
int * a= (int*)malloc(size*sizeof(int));
int value=0;
//initialise a with even numbers
for(long unsigned int iterator = 0 ;iterator < size;iterator++)
{
a[iterator]= value ;
value+=2;
}
return a;
}
int* f1(int* b)
{
for(long unsigned int iterator = 0;  iterator < size ; iterator++)
{
printf("%d  ",b[iterator]);
}
return b;
}
OUTPUT:-
10  12  14  16  18  20  22  24  26  28  30  32  34  36  38  40  42  44  46  48
50  52  54  56  58  60  62  64  66  68  70  72  74  76  78  80  82  84  86  88
90  92  94  96  98  100  102  104  106  108
0  2  4  6  8  10  12  14  16  18  20  22  24  26  28  30  32  34  36  38  40  4
2  44  46  48  50  52  54  56  58  60  62  64  66  68  70  72  74  76  78  80  8
2  84  86  88  90  92  94  96  98

Here we allocated memory by malloc for a in function f and call function  then print its value in main we get the same value which is initialized in function f().In case of bb the value is initialized in main same printed in f1().Thus we must say that the array allocated by malloc is safe to return.

Now we can discuss returning an array allocated statically .There are two cases occur :-

1)If we declare an array with static duration
2)if we declare an array with automatic duration

1)If we declare an array with static duration:-If we declare an array in function f1 with static duration the value will be the remain safe in the main we can check it ny printing it.

2)if we declare an array with automatic duration:-If we declare an array in f() with automatic duration which is default duration .Then there the value will be unsafe . It means the auto variables are destroyed after there use and memory is cleaned up.

NOTE:-It may be possible if we returning an array from a function f which is allocated staticaly and have static duration the value of array in function main is same because sometimes memory is not cleaned up and in that case value will be same.

Here is the program for the issues related with returning an array having static allocation:-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h> 
#include<math.h>
#define size 50
int* f();
int* staticFun();

void main()
{
int *aa=f();
int* bb=staticFun();
//print aa in loop;
for(long unsigned int iterator = 0;  iterator < size ; iterator++)
{
printf("%d  ",aa[iterator]);
}

printf("\n"); 

for(long unsigned int iterator = 0;  iterator < size ; iterator++)
{
printf("%d  ",bb[iterator]);
}
_getch();
}
int* f() 
{
int  a[size];
int value = 0;
//initialise a with even numbers
for(long unsigned int iterator = 0 ;iterator < size;iterator++)
{
a[iterator]= value ;
value  += 2;
}
return a;
}
int* staticFun()
{
static int b[size];
int value=10;
for(long unsigned int iterator = 0 ;iterator < size;iterator++)
{
b[iterator]= value ;
value  += 2;
}
return b;
}
OUTPUT:-

-858993460  7801500  4585992  1547167480  1  1547167469  2094676724  4586380  45
86128  2130567168  1  1  1  3  7806216  7800832  4586096  1547215168  547612116
 -2  4586024  1546466082  4586380  2130567168  4586128  4586024  1546360630  154
7513552  4586036  1546458873  17  4586112  1546485755  1  1547498680  1546485737
  2094676604  4586380  4586128  2130567168  1  1  3  4586124  -858993460  -85899
3460  4586444  1547215168  547632892  -2
10  12  14  16  18  20  22  24  26  28  30  32  34  36  38  40  42  44  46  48
50  52  54  56  58  60  62  64  66  68  70  72  74  76  78  80  82  84  86  88
90  92  94  96  98  100  102  104  106  108

We can see here from the output that the array declared as auto duration prints the other value in the main than intialized in f() while the array declared as a static prints the same value in the main as initialized in f1().

Saturday 6 April 2013

Storage class specifier


Storage class specifier declares that a variable or function declred in a program where stored.There are following types of storage specifier in C :-
1)auto
2)register
3)extern
4)static
5)typedef
6)__declspec
7)mutable
8)thread_local


(1)auto:-auto is a keyword used to declare an automatic storage class.It is declared as following types :-

auto  a=2;              //auto
auto  b=3.8;            //float
auto c='h';            //char

 auto  b1=3.8f;          //float 
 auto  b2=3.8F;          //float
 auto  b3=3.8l;         //double
 auto  b4=3.8L;          //long double 
 printf("a=%d\n",a);    //int 
printf("b=%f\n",b);    // float
printf("c =%c\n",c);   //char

2)resister:-resister is also a storage class used to faster access of variable because the storage will be done in CPU registers .It is a hint to the compiler that the variable will be heavily used and that  recommend it will be kept in a processor register if possible.We can declare a datatype register in following manner:-

register int ri=98;

3)extern:-extern is also a storage class specifier .It is used for the use a variable which is initialized in another file in same project.When we use extern modifier with any variables it is only declaration i.e. memory is not allocated for these variable.We can declare register keyword in following manner:-

extern int ei=23;

4)Static:-static is also a storage class specifier used in C/C++.It also stores variable in memory.The default initial value is zero.The value of the variable persists between different function calls.We can use a static datatype  in following manner:-

  

#include <stdio.h>

void func() {
        static int x = 0; // x is initialized only once across three calls of func()
        printf("%d\n", x); // outputs the value of x
        x = x + 1;
}

int main(int argc, char * const argv[]) {
        func(); // prints 0
        func(); // prints 1
        func(); // prints 2
        return 0;
}


(5)typedef:-typedef keyword provide us to rename a variable datatype into a short and meaningful way.
Ex:-
                typedef unsigned long int ULI;
                 ULI a;



13)_declspec:-It is a storage class modifier  used with many extended attribute like dllimport and dllexport.



7)mutable:-This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function.

mutable member-variable-declaration;

8)thread_local:-The variable is allocated when the thread begins and deallocated when the thread ends. Each thread has its own instance of the variable. Only variables declared thread_local have this storage duration. thread_local can only be declared for global variables, plus those declared with static or extern.It is declared as following:-


 thread_local unsigned int rage = 1


Here are some inportant notes about storage class specifiers:-

C program instructions get stored in code/text segment
Register variables are stored in Register. 
The memory created dynamically are stored in Heap.
Local Variables/arrays (Except static) are stored in Stack.  
 Global, extern & static variables/arrays are stored in data segment.

 a) Uninitialized static/global/extern variables are stored in the BSS(Block started by symbol) of the data     segment .ie high address..
               (Note: Uninitialised static variable is automatically initialised to zero)
               (Note: Uninitialised global variable is automatically initialised to zero)
               (Note: Uninitialised extern variable is automatically initialised to zero)
 b) Initialized static/global/extern variables are stored in data section of the data segment. ie low address
               (Initialised static also includes zero initialised static variable)

const local variable(initialised) is stored on stack.
const local var (uninitialized) is NOT POSSIBLE. It must be initialized when declared.
const global var (initialized) is stored in data section of data segment.
const global var (uninitialized) is NOT POSSIBLE. It must be initialized when declared.
-----------
null pointer ->   .bss
static pointer (uninitialised)-> (initialized to null by default) -> null pointer ->   .bss
command line arguments (stack)
function parameters (stack)

----------
Data in the bss segment is initialized by the kernel to zero before the program starts executing.
------------
Default storage class specifiers:
For external declarations (outside a function) the default storage class specifier will be extern and for internal declarations(inside a function) it will be auto.

default storage class specifier for functions  is always extern.
We can understand this more easily by following details:-

Object Storage Class Specifiers Storage Duration (Life Time) Linkage Scope (Accesibility/Visibility) Storage Area
Internal variable auto Automatic No Function/Block/Compound Stmt SS:stack     Initialized with garbage value
Internal variable register Automatic No Function/Block/Compound Stmt Register
Internal variable static static No Function/Block/Compound Stmt DS Uninitialized  DS:BSS Initialized with zero
Internal variable extern static (???) external (???) Function/Block/Compound Stmt None Initialized  DS:data
Internal variable none (default auto) Automatic No Function/Block/Compound Stmt SS:stack     Initialized with garbage value
Internal Function auto static (???) external (???) Project (multiple files) CS
Internal Function register invalid invalid invalid invalid
Internal Function static invalid invalid invalid invalid
Internal Function extern static (???) external (???) Project (multiple files) CS
Internal Function none (default extern) static (???) external (???) Project (multiple files) CS
External variable auto static external Project (multiple files) DS  
External variable register invalid invalid invalid invalid  
External variable static static internal File DS Uninitialized  DS:BSS Initialized with zero
External variable extern static external Project (multiple files) DS/None Initialized  DS:data
External variable none (default extern) static external Project (multiple files) DS  
External Function auto static external Project (multiple files) CS
External Function register invalid invalid invalid invalid
External Function static static internal File CS   Storage Area
External Function extern static external Project (multiple files) CS extern int i; None intialized to 5
External Function none (default extern) static external Project (multiple files) CS int i=5;  
   
thread_local thread No extern int i=6; DS:data intialized to 6
dynamic mem allocation Dynamic No   SS:Heap    
extern int i; None intialized to 0
Automatic No int i;  
Thread No
Dynamic No