true

Find the best tutors and institutes for BSc Tuition

Find Best BSc Tuition

Please select a Category.

Please select a Locality.

No matching category found.

No matching Locality found.

Outside India?

Search for topics

BSc Tuition Updates

Ask a Question

Post a Lesson

All

All

Lessons

Discussion

Answered on 16/03/2019 Tuition/BSc Tuition/BSc Computer Science

How to do correspondence T.Y B.Sc(IT) course with a new syllabus from Mumbai University, after 4 years gap?

Ruhinaz

Tutor

Clear the basic studies already done in 1st n 2nd year of bsc subject then go through the syllabus and note down the things u know then u cann make ur own notes and google will help u in that as per a tutor take help of best IT tutor for hard topics who can make you understand better than 1st read more

Clear the basic studies already done in 1st n 2nd year of bsc subject then go through the syllabus and note down the things u know then u cann make ur own notes  and google will help u in that as per a tutor take help of best IT tutor for hard topics  who can make you understand better than 1st

read less
Answers 1 Comments
Dislike Bookmark

Lesson Posted on 23/12/2017 Tuition/BSc Tuition/BSc Computer Science

C++: Passing A Function As an Argument

Ashutosh Singh

I have been teaching computer science & engineering on multiple platforms. I have a rich experience of...

#include using namespace std; int sum(int a,int b) { return a+b; } void f2(int (*f)(int,int),int a,int b) //'*f' is a POINTER TO A FUNCTION whose RETURN TYPE is //'int' and arg type (int,int) . Here, '*f' is FORMAL PARAMETER { ... read more

#include
using namespace std;

int sum(int a,int b)
{
   return a+b;
}
void f2(int (*f)(int,int),int a,int b) //'*f' is a POINTER TO A FUNCTION whose RETURN TYPE is                                                           //'int' and arg type (int,int)  . Here, '*f' is FORMAL PARAMETER
{                                                                
  cout<<sum(a,b)<<endl;
}
int main()
{   int (*p1)(int,int)=∑          //Here, '*pf1' is ACTUAL PARAMETER
    f2(sum,10,20);                         //NAME OF A FUNCTION IS ITSELF A POINTER TO ITSELF
    f2(p1,20,79);
    return 0;

}

read less
Comments
Dislike Bookmark

Lesson Posted on 07/08/2017 Tuition/BTech Tuition/BTech Computer Science Engineering Tuition/BSc Tuition/BSc Computer Science

Deadlocks In Distributed Systems

SR-IT Academy

SR - IT Academy is one of the leading tutorial point providing services like tutoring and computer training...

Deadlocks in Distributed Systems: Deadlock can occur whenever two or more processes are competing for limited resources and the processes are allowed to acquire and hold a resource (obtain a lock) thus preventing others from using the resource while the process waits for other resources. Two common... read more

Deadlocks in Distributed Systems:

Deadlock can occur whenever two or more processes are competing for limited resources and the processes are allowed to acquire and hold a resource (obtain a lock) thus preventing others from using the resource while the process waits for other resources.

Two common places where deadlocks may occur are with processes in an operating system (distributed or centralized) and with transactions in a database.

  • Deadlocks in distributed systems are similar to deadlocks in single processor systems, only worse:

    • They are harder to avoid, prevent or even detect.

    • They are hard to cure when tracked down because all relevant information is scattered over many machines.

  • People sometimes might classify deadlock into the following types:

    • Communication deadlocks : Competing with buffers for send/receive

    • Resources deadlocks : Exclusive access on I/O devices, files, locks, and other resources

  • Four best-known strategies to handle deadlocks:

    • The ostrich algorithm (ignore the problem).

    • Detection (let deadlocks occur, detect them, and try to recover).

    • Prevention (statically make deadlocks structurally impossible).

    • Avoidance (avoid deadlocks by allocating resources carefully).

Deadlock Detection:

Deadlock detection attempts to find and resolve actual deadlocks.  These strategies rely on a Wait-For-Graph (WFG) that in some schemes is explicitly built and analyzed for cycles.   In the WFG, the nodes represent processes and the edges represent the blockages or dependencies.  Thus, if process A is waiting for a resource held by process B, there is an edge in the WFG from the node for process A to the node for process B. 

 In the AND model (resource model), a cycle in the graph indicates a deadlock.  In the OR model, a cycle may not mean a deadlock since any of a set of requested resources may unblock the process.  A knot in the WFG is needed to declare a deadlock.  A knot exists when all nodes that can be reached from some node in a directed graph can also reach that node.

In a centralized system, a WFG can be constructed fairly easily.  The WFG can be checked for cycles periodically or every time a process is blocked, thus potentially adding a new edge to the WFG.   When a cycle is found, a victim is selected and aborted.

 Centralized Deadlock Detection:

 We use a centralized deadlock detection algorithm and try to imitate the nondistributed algorithm.

  • Each machine maintains the resource graph for its own processes and resources.

  • A centralized coordinator maintain the resource graph for the entire system.

  • When the coordinator detect a cycle, it kills off one process to break the deadlock.

  • In updating the coordinator’s graph, messages have to be passed.

  • Method 1) Whenever an arc is added or deleted from the resource graph, a message have to be sent to the coordinator.

  • Method 2) Periodically, every process can send a list of arcs added and deleted since previous update.

  • Method 3) Coordinator ask for information when it needs it.

 

False Deadlocks :

  • When the coordinator gets a message that leads to a suspect deadlock:

  • It send everybody a message saying “I just received a message with a timestamp T which leads to deadlock. If anyone has a message for me with an earlier timestamp, please send it immediately”

  • One possible way to prevent false deadlock is to use the Lamport’s algorithm to provide global timing for the distributed systems.

  • When every machine has replied, positively or negatively, the coordinator will see that the deadlock has really occurred or not.

The Chandy-Misra-Haas algorithm:

  • Processes are allowed to request multiple resources at once the growing phase of a transaction can be speeded up.

  • The consequence of this change is a process may now wait on two or more resources at the same time.

  • When a process has to wait for some resources, a probe message is generated and sent to the process holding the resources. The message consists of three numbers: the process being blocked, the process sending the message, and the process receiving the message.

  • When message arrived, the recipient checks to see it it itself is waiting for any processes. If so, the message is updated, keeping the first number unchanged, and replaced the second and third field by the corresponding process number.

  • The message is then send to the process holding the needed resources.

  • If a message goes all the way around and comes back to the original sender -- the process that initiate the probe, a cycle exists and the system is deadlocked.

  • There are several ways to break the deadlock:

  • The process that initiates commit suicide : this is overkilling because several process might initiates a probe and they will all commit suicide in fact only one of them is needed to be killed.

  • Each process append its id onto the probe, when the probe come back, the originator can kill the process which has the highest number by sending him a message. (Hence, even for several probes, they will all choose the same guy)

The Probe Scheme:

The scheme proposed by Chandy, Misra and Haas [1] uses local WFGs to detect local deadlocks and probes to determine the existence of global deadlocks.  If the controller at a site suspects that process A, for which it is responsible, is involved in a deadlock it will send a probe message to each process that A is dependent on.  When A requested the remote resource, a process or agent was created at the remote site to act on behalf of process A to obtain the resource.  This agent receives the probe message and determines the dependencies at the current site.

The probe message identifies process A and the path it has been sent along.  Thus, the message probe(i,j,k) says that it was initiated on behalf of process i and was sent from the controller for agent j (which i is dependent on) to the controller for agent k.

When an agent whose process is not blocked receives a probe, it discards the probe.  It is not blocked so there is no deadlock.   An agent that is blocked sends a probe to each agent that it is blocked by.  If process i ever receives probe(i,j,i), it knows it is deadlocked.

This popular approach, often called "edge-chasing", has been shown correct in that it detects all deadlocks and does not find deadlocks when none exist.

In the OR model, where only one out of several requested resources must be acquired, all of the blocking processes are sent a query message and all of the messages must return to the originator in order for a deadlock to be declared.  The query message is similar to a probe, but has an additional identifier so the originator can determine whether or not all the paths were covered.

There are several variations to these algorithms that seek to optimize different properties such as: number of messages, length of messages, and frequency of detection. One method proposed by Mitchell and Merritt for the single-resource model, sends information in the opposite direction from the WFG edges .

Deadlock Prevention:

Prevention is the name given to schemes that guarantee that deadlocks can never happen because of the way the system is structured.   One of the four conditions for deadlock is prevented, thus preventing deadlocks. 

Collective Requests:

One way to do this is to make processes declare all of the resources they might eventually need, when the process is first started.  Only if all the resources are available is the process allowed to continue.  All of the resources are acquired together, and the process proceeds, releasing all the resources when it is finished.  Thus, hold and wait cannot occur.

The major disadvantage of this scheme is that resources must be acquired because they might be used, not because they will be used.  Also, the pre-allocation requirement reduces potential concurrency.

Ordered Requests

Another prevention scheme is to impose an order on the resources and require processes to request resources in increasing order.  This prevents cyclic wait and thus makes deadlocks impossible.

One advantage of prevention is that process aborts are never required due to deadlocks.  While most systems can deal with rollbacks, some systems may not be designed to handle them and thus must use deadlock prevention.

  • A method that might work is to order the resources and require processes to acquire them in strictly increasing order. This approach means that a process can never hold a high resource and ask for a low one, thus making cycles impossible.

  • With global timing and transactions in distributed systems, two other methods are possible -- both based on the idea of assigning each transaction a global timestamp at the moment it starts.

  • When one process is about to block waiting for a resource that another process is using, a check is made to see which has a larger timestamp.

  • We can then allow the wait only if the waiting process has a lower timestamp.

  • The timestamp is always increasing if we follow any chain of waiting processes, so cycles are impossible --- we can used decreasing order if we like.

  • It is wiser to give priority to old processes because

    • they have run longer so the system have larger investment on these processes.

    • they are likely to hold more resources.

    • A young process that is killed off will eventually age until it is the oldest one in the system, and that eliminates starvation.

Preemption:

Wait-die Vs. Wound-wait:

  • Definition it can be restarted safely later.

i. Wait-die:

  • If an old process wants a resource held by a young process, the old one will wait.

  • If a young process wants a resource held by an old process, the young process will be killed.

  • Observation: The young process, after being killed, will then start up again, and be killed again. This cycle may go on many times before the old one release the resource.

  • Once we are assuming the existence of transactions, we can do something that had previously been forbidden: take resources away from running processes.

  • When a conflict arises, instead of killing the process making the request, we can kill the resource owner. Without transactions, killing a process might have severe consequences. With transactions, these effects will vanish magically when the transaction dies.

ii. Wound-wait:

  • If an old process wants a resource held by a young process, the old one will preempt the young process, wounded and killed, restarts and wait.

  • If a young process wants a resource held by an old process, the young process will wait.

read less
Comments
Dislike Bookmark

Looking for BSc Tuition

Find best BSc Tuition in your locality on UrbanPro.

FIND NOW

Lesson Posted on 05/07/2017 Tuition/BTech Tuition/Design & Analysis of Algorithms Tuition/BTech Tuition/BTech Computer Science Engineering Tuition/BTech Tuition/BTech Information Science Engineering +2 Tuition/BSc Tuition/BSc Computer Science Tuition/BCA Tuition less

Introductory Discussions On Complexity Analysis

Shiladitya Munshi

Well, I love spending time with students and to transfer whatever computing knowledge I have acquired...

What is Complexity Analysis of Algorithm? Complexity Analysis, simply put, is a technique through which you can judge about how good one particular algorithm is. Now the term “good” can mean many things at different times. Suppose you have to go from your home to the Esplanade! There are... read more

What is Complexity Analysis of Algorithm?

Complexity Analysis, simply put, is a technique through which you can judge about how good one particular algorithm is.  Now the term “good” can mean many things at different times.

Suppose you have to go from your home to the Esplanade! There are many ways from your home that may lead to Esplanade. Take any one, and ask whether this route is good or bad. It may so happen that this route is good if the time of travel is concerned (that is the route is short enough), but at the same time, it may be considered bad taking the comfort into considerations (This route may have many speed breakers leading to discomforts). So, the goodness (or badness as well) of any solution depends on the situations and whatever is good to you right now, may seem as bad if the situation changes. In a nutshell, the goodness/badness or the efficiency of a particular solution depends on some criteria of measurements.

So what are the criteria while analyzing complexities of algorithms?

Focusing only on algorithms, the criteria are Time and Space. The criteria Time, judges how fast or slow the algorithms run when executed; and the criteria Space judges how big or small amount of memory (on primary/hard disks) is required to execute the algorithm. Depending on these two measuring criteria, two type of Algorithm Analysis are done; one is called Time Complexity Analysis and the second one is Space Complexity Analysis.

Which one is more important over the other?

I am sorry! I do not know the answer; rather there is no straight forward answer to this question. Think of yourself. Thinking of the previous example of many solutions that you have for travelling from your home to Esplanade, which criteria is most important? Is it Time of Travel, or is it Comfort? Or is it Financial Cost? It depends actually. While you are in hurry for shopping at New Market, the Time Taken would probably be your choice. If you have enough time in your hand, if you are in jolly mood and if you are going for a delicious dinner with your friends, probably you would choose Comfort; and at the end of the month, when you are running short with your pocket money, the Financial Cost would be most important to you.  So the most important criterion is a dynamic notion that evolves with time.

Twenty or thirty years back, when the pace of advancement of Electronics and Computer Hardware was timid, computer programs were forced to run with lesser amount of memory.  Today you may have gigantic memory even as RAM, but that time, thinking of a very large hard disk was a day dreaming! So at that time, Space Complexity was much more important than the Time Complexity, because we had lesser memory but ample times.

Now the time has changed! Now a day, we generally enjoy large memories but sorry, we don’t have enough time with us. We need every program to run as quick as possible! So currently, Time Complexity wins over Space Complexity.  Honestly, both of these options are equally important from theoretical perspective but the changing time has an effect to these.         

read less
Comments
Dislike Bookmark

Lesson Posted on 05/07/2017 Tuition/BTech Tuition/Design & Analysis of Algorithms Tuition/BTech Tuition/BTech Computer Science Engineering Tuition/BTech Tuition/BTech Information Science Engineering +2 Tuition/BCA Tuition Tuition/BSc Tuition/BSc Computer Science less

Getting A Bit Deeper Into Time Complexity Analysis

Shiladitya Munshi

Well, I love spending time with students and to transfer whatever computing knowledge I have acquired...

What is Time Complexity Analysis? In the last blog, you got a rough idea about the Time Complexity and that was all about to judge how fast the algorithm can run, or putting it in another way, how much time an algorithm should require while running. Suppose, someone asks you that how fast you can do... read more

What is Time Complexity Analysis?

In the last blog, you got a rough idea about the Time Complexity and that was all about to judge how fast the algorithm can run, or putting it in another way, how much time an algorithm should require while running.

Suppose, someone asks you that how fast you can do a job or how much time do you require finishing a job. Most probably, your answer will be any of these threes (A) at most time t or (B) at least time t or (C) exactly time t. Whatever your answer might be, your answer must have been guided by identification of the number of basic operation needed to complete the job. So unless and until you do have a clear cut idea of how many basic operations are needed to be performed, you cannot say how much time you do require finishing a job, Right?

Similar is the case of answering how much time is required executing an algorithm. You need to identify first that how many basic operations (like comparison, memory access etc.) this algorithm performs. Once you figure it out, then you are all set to compute how fast you can do these all.

This computation is not an easy business. It is done through establishing a relationship between the run time (execution time) of the given algorithm and the input size of the problem, which the given algorithm is supposed to solve. Sounds weird?  You might be wondering what about the “number of basic operations needed”? Why did you identified that all?

Genuine, your doubts are well accepted. But the thing is, the number of basic operations needed for an algorithm depends on the input size of the problem and that is why we are really interested to have a relationship between the run time and the input size.  This relationship actually gives you a clear idea about the time required to run an algorithm and hence about the time complexity. 

What is the physical significance of this relationship? What are its features?

Well, a relationship between the run time and input size gives you the nature of the growth of time complexity. The growth indicates physically that on increasing the input size, how the run time changes. This relationship has a form of function which does not deal with any exact quantification; rather, it is expressed as a proportion called the “Order”.  Suppose, if the run time of an algorithm increases with the same proportion of the increase in input size, then the run time is of linear order.

Why do we need to know about the run time complexity? What are the objectives?

The objective of computing run time complexity is twofold. Firstly it gives a measure of efficiency of an algorithm with respect to run/execution time and secondly, in presence of multiple algorithms for a specific problem, it helps in deciding which one to choose for implementation. That means comparison among different algorithms for the same problem is a huge benefit that we can derive from Time Complexity analysis.       

How does the Time Complexity Analysis get realized?

There are mainly three classes of Time Complexity Analysis. (A) Worst Case Analysis – It estimates the upper bound of the number of basic operations needed to be performed if the algorithm is to be executed, and (B) Best Case Analysis – It estimates the lower bound of the number of operations needed to be performed if the algorithm is to be executed, and lastly (C) Average Case Analysis – any estimation in between.

If not said otherwise, in the rest of all our discussions, Time Complexity Analysis will always indicate the Worst Case Analysis.

Characteristics of computing Time Complexity

While computing time complexity, generally following characteristics are maintained –

  1. If any number of basic operations get identified which are independent of input size of the problem, the time complexity for that gets identified with Constant order.
  2. While comparing multiple algorithms, the Time Complexity analysis should ignore the common tasks       
  3. If the Time Complexity expression is realized with a polynomial, then the order of time complexity is dictated by the highest order of the polynomial

Give me one example

Let us suppose we need to compute f(x) = 7x^4 + 6x^3 -5x^2 + 8x -5.

To compute this polynomial, we can consider two algorithms, (A) Brute Force Algorithm and (B) Horner’s Algorithm.

Brute Force Algorithm computes f(x) as 7*x*x*x*x + 6*x*x*x - 5*x*x + 8*x -5 and Horner’s Algorithm computes f(x) as (((7*x + 6)*x – 5)*x + 8)*x – 5.

Both the algorithms perform two additions and two subtractions apart from some number of multiplications which are different for the two cases. Hence we will ignore the basic operations addition and subtraction and will concentrate only on the number of multiplications.

Brute Force Algorithm, according to the example, for an input size n does k number of multiplications where k = n + (n-1)+(n-2)+……+2+1+0 = (n(n-1))/2.

On the other hand Horner’s Algorithm, as seen in the example, for an input size n,  does k’ number of multiplications where k’ = n.

So the order of Time Complexity of Brute Force Algorithm is expressed by the polynomial (n(n-1))/2 I,e n^2/2 + n/2. Hence finally the order of time complexity for Brute Force Algorithm will be dictated by n^2. It means the run time complexity of the Brute Force Algorithm increases proportional to the square of the input size.

In comparison, the time complexity of Horner’s algorithm is dictated by the term n only, which means that the increase in run time of Horner’s algorithm is linearly proportional to the input size.

It is evident from the discussion that the Horner’s Algorithm has a better run time than Brute Force Algorithm for computation of polynomial expressions.          

read less
Comments
Dislike Bookmark

Lesson Posted on 05/07/2017 Tuition/BTech Tuition/Design & Analysis of Algorithms Tuition/BTech Tuition/BTech Computer Science Engineering Tuition/BTech Tuition/BTech Information Science Engineering +2 Tuition/BCA Tuition Tuition/BSc Tuition/BSc Computer Science less

Understanding Asymptotic Notations And Big Oh(O)

Shiladitya Munshi

Well, I love spending time with students and to transfer whatever computing knowledge I have acquired...

What are asymptotic notations for complexity analysis?A problem may have numerous algorithmic solutions. In order to choose the best algorithm for a particular task, you need to be able to judge how long a particular solution will take to run. Or, more accurately, you need to be able to judge how long... read more

What are asymptotic notations for complexity analysis?

A problem may have numerous algorithmic solutions. In order to choose the best algorithm for a particular task, you need to be able to judge how long a particular solution will take to run. Or, more accurately, you need to be able to judge how long two solutions will take to run, and choose the better of the two. You don't need to know how many minutes and seconds they will take, but you do need some way to compare algorithms against one another.

Asymptotic notations are just used for this, i,e they are used for comparing two functions of two different algorithms. 

Let us suppose I write f(n) = W(g(n)) where W is an asymptotic notation. Here this expression says how the function f(x) grows in comparison to another function g(n).

What are the most common Asymptotic Notations used in Complexity Analysis?   

Most common asymptotic notations used for time complexity analysis are Big Oh (O), Big Theta (Θ), Big Omega (Ω), Small Oh (o) and Small Omega (ω). Let us discuss them one by one

How to describe Big Oh (O) ?
If run time of an algorithm is of O(g(n)), it means that the running time of the algorithm (as n gets larger) is at most proportional to g(n). Hence it helps in estimating an upper bound of the number of basic operations to be performed.

Mathematically, a function f(x) is equal to Big Oh of another function g(x), i,e f(x) = O(g(x) is true if and only if there exists two constants (C1 and C2)such that

a) C1 and C2 are always positive
b) 0<= f(n) <= C1*g(n) for any value of n => C2

Let us have an example for this with f(n) being 2n^2 and g(n) being n^3. 
Let us check whether 2n^2 = O(n^3) is true or not 

if we take C1 = 1 and C2 = 2 (all positive maintaining condition described in a), then for n = 3 (that is value of n greater than value of C2), we have the following relation true

0<= 1*(2*3^2)<= 3^3. 

Hence 2n^2 = O(n^3) is true for C1 = 1 and C2 = 2.

read less
Comments
Dislike Bookmark

Lesson Posted on 05/07/2017 Tuition/BTech Tuition/BTech Computer Science Engineering Tuition/BTech Tuition/BTech Information Science Engineering Tuition/BSc Tuition/BSc Computer Science +1 Tuition/BCA Tuition less

An Interesting Discussion About Malloc And Calloc

Shiladitya Munshi

Well, I love spending time with students and to transfer whatever computing knowledge I have acquired...

What are malloc and calloc? Simply putting they are the predefined functions in C language. Malloc( ) and calloc( ) are two such functions which are used for more or less identical purpose and that is to allocate memories for any variable dynamically during execution time of the program. Give me a... read more

What are malloc and calloc?

Simply putting they are the predefined functions in C language.

Malloc( ) and calloc( ) are two such functions which are used for more or less identical purpose and that is to allocate memories for any variable dynamically during execution time of the program.

Give me a brief of malloc:

So as I have said malloc is a function; malloc must have three valid components as all other functions do have. These are (a) function name (b) function arguments and (c) function return type, that is, malloc must have a signature or prototype. Now what is the prototype of malloc? It is like following:

(void*) malloc(unsigned int) [Note: The actual prototype is slightly different than this, but for the time being this simplification will work]

It shows that the function name is malloc itself, it expects an unsigned integer as argument and it returns a void pointer or generic pointer.  So let us discuss a bit about them.

As per the prototype, malloc expects an unsigned integer. To assimilate this, let us recall why should we use malloc? Malloc is used to allocate a chunk of memory at program run time dynamically. So we must let malloc know what the size of that chunk of memory is. Suppose we want malloc to allocate a chunk of memory where we can store 10 integers. In this case, we actually want malloc to allocate 20 bytes of memory (if we are running our program on windows). And we do it by supplying the size 20 as an argument. So the unsigned integer that is passed to malloc is actually the requirement of memory in bytes; and it is evident that the memory requirement cannot be negative any time, so the data type is unsigned.     

Now what that void pointer is doing at the beginning as return type? To understand this, we have to recall that a function gives a feedback to its caller through the return type. So after allocating the memory (I admit, you do not how) malloc has to return the base pointer, I,e, the address of the starting location of the memory chunk allocated. Though void pointer, malloc actually returns this base address.

I am sure you will scream out “why void?” Wait a minute. Answer me, who has written this malloc function? Is it you or someone else? Obviously it is not you, malloc function is written by someone else. Now the original developer of malloc had no idea for which purpose you would be using this malloc. Currently, you can use malloc to allocate memory for storing some integers, or some floats or some structures defined by you. There are so many options and those options are equally likely for you. You as a programmer currently know that this malloc is being used for storing some integers or whatever else, but the original programmer had no idea about that. So malloc returns void pointer or generic pointer, a special one which can point to any type of memory generically. So it is your responsibility to properly type cast this void pointer. If you are using it to store some integers, cast void* as int*, if you are using malloc to store some Node type structures, then cast it to Struct Node*. Got it?

One last point still exists. You must have seen malloc argument to contain sizeof(), right? Why it is so?

As I have mentioned that the memory requirement is informed through the argument, it is highly possible that the memory requirement may change as the OS changes. For example in one system you may require 20 bytes to store 10 integers, while it may be 40 bytes in other system or OS. So if I hardcode my memory requirement as 20 or 40 for any specific platform, it won’t suffice the scenarios generated by other systems. So to meet the portability issue, that may rise up later, we as a programmer should not deal with the memory requirement directly. We should inform the compiler that  that we need to store n number of elements only and let the compiler decide what the size of each such element is by using sizeof.

So we should call malloc with an argument (n * sizeof(int)) if we want to store n number of integers. By doing this, we are actually letting the C compiler to calculate the memory requirement (under the current OS) of one element and multiplying this with n, compiler can compute the exact memory requirement as per the current system.

As a good programmer you should never hardcode your memory requirement, it may end up in a serious problem if your program gets ported to any other OS.

Look at the following example for clear undestanding:

To store 15 characters, do like:

char *pointerToCharArray;

int size = 15;

pointerToCharArray = (char*)malloc(size*sizeof(char));

To store n numbers of MyStructure type of structure, do like:

struct MyStructure *pointerToMyStructureArray;

pointerToMyStructureArray = (struct MyStructure*)malloc(n*sizeof(struct MyStructure));

To store k numbers of integers, do like:

int* point;

point = (int*)malloc(k*sizeof(int));

Once you are done with these, you can use your pointer (like pointerToCharArray or pointerToMyStructureArray or point as seen in the examples) like an array with indexing. That means now point[5] will give you the integer stored at 5th index of point or the sixth integer stored within the memory chunk, base address of which, is being pointed by a pointer point.

So what is calloc then? How it is different from malloc?

Calloc is another function which, like malloc, is used for dynamic memory allocations.

Malloc if called to allocate a memory space that can store 10 integers (under windows),occupies the memory as a single chunk of 20 bytes, where calloc, if called for the same purpose, occupies 20 bytes, but not as a single chunk of memory, rather , it occupies 10 blocks of memory, each having 2 bytes (as it is under windows, as we have supposed). Hence calloc has the following prototype:

(void*) calloc(unsigned int, unsigned int)

The first unsigned int is for number of elements that you want to store and the second unsigned int is for memory allocation needed for storing a single element.

This is why calloc can occupy the memory space with multiple blocks, each of equal size. The void* is doing the same thing as that of malloc

So look at the following example for clear understanding:

To store 15 characters, do like

char *pointerToCharArray;

int size = 15;

pointerToCharArray = (char*)calloc(size, sizeof(char));

To store n numbers of MyStructure type of structure, do like:

struct MyStructure *pointerToMyStructureArray;

pointerToMyStructureArray = (struct MyStructure*)calloc(n, sizeof(struct MyStructure));

To store k numbers of integers, do like:

int* point;

point = (int*)calloc(k, sizeof(int));

So the syntactical difference is malloc takes one argument, while calloc takes two. But you need to have an idea why it is so. I think the above discussion tells you that.

Another point of difference is like following:

Malloc allocates the memory chunk and initializes the memory with garbage values, whereas calloc allocates the multiple block of memory chunks and initializes those with 0s (zeros)

So we come to an end of this discussion. I am open to clear your doubts if any.

read less
Comments
Dislike Bookmark

Lesson Posted on 05/07/2017 Tuition/BTech Tuition/BTech Computer Science Engineering Tuition/BTech Tuition/BTech Information Science Engineering Tuition/BSc Tuition/BSc Computer Science +1 Tuition/BCA Tuition less

What Are The Two Forms Of #Include?

Shiladitya Munshi

Well, I love spending time with students and to transfer whatever computing knowledge I have acquired...

There are two variants of #include. The one is #include and the other one is #include”file”. In general the first form that is #include is used to include system defined header files which are searched in the standard list of system directories. The second form i,e #include”file”... read more

There are two variants of #include. The one is #include and the other one is #include”file”. In general the first form that is #include is used to include system defined header files which are searched in the standard list of system directories. The second form i,e #include”file” is generally used to include user defined header files. These files are searched first in the current directory, if failed, then secondly in the standard list of system directories.

Both the forms of #include share a common property that is no escape sequence or commenting  styles are recognized within or “file”. What I mean to say is that if I write #include <x/*y>, that means I want to include a file named x/*y.  Similarly writing #include<x\y\\z> is also perfect if the file x\y\\z is needed to be included.

read less
Comments
Dislike Bookmark

Lesson Posted on 05/07/2017 Tuition/BTech Tuition/BTech Computer Science Engineering Tuition/BTech Tuition/BTech Information Science Engineering Tuition/BCA Tuition +1 Tuition/BSc Tuition/BSc Computer Science less

What Is the Difference Between Function And Subroutine?

Shiladitya Munshi

Well, I love spending time with students and to transfer whatever computing knowledge I have acquired...

The difference is indeed very thin and it depends on the context. In general Function is a piece of code with a name, inputs (arguments) and an output (return types). That is function should always return. Some programming languages are there which uniquely maps inputs to the corresponding outputs. But... read more

The difference is indeed very thin and it depends on the context. In general Function is a piece of code with a name, inputs (arguments) and an output (return types). That is function should always return. Some programming languages are there which uniquely maps inputs to the corresponding outputs. But surely C is not such.  There is also a convention (but not a very strict one) that a function should not change any global variable. In C language, a function is always a realistic part of the code.

Subroutine is just a piece of any sorts of code with a definite entry and exit point. It should not return anything and a subroutine can always change global variables. These are generally used for conceptual purposes like in psudocodes.

read less
Comments
Dislike Bookmark

Looking for BSc Tuition

Find best BSc Tuition in your locality on UrbanPro.

FIND NOW

Lesson Posted on 07/06/2017 Tuition/BCA Tuition IT Courses/Computer Course Tuition/BSc Tuition +3 Tuition/BSc Tuition/BSc Computer Science Tuition/BSc Tuition/Information Security Tuition/BSc Tuition/Internet Technologies less

Malware

Mohamed Badar Bawni

4 year of teaching experience my number is nine eight two one seven eight six nine six nine have been...

Malware Vivek like any other teenage boy loves to play online games on his phone. He usually downloads the free games available at the trusted market zones. One day, he got an SMS “Click here to get the Latest Paid Games Online for free“. Excitedly, he clicked on the link and downloaded... read more
Malware
 
Vivek like any other teenage boy loves to play online games on his phone. He usually downloads the free games available at the trusted market zones.
 
One day, he got an SMS “Click here to get the Latest Paid Games Online for free“. 



Excitedly, he clicked on the link and downloaded and installed the game. Unknowingly to him, these 
games had a malicious part that allowed the attacker to take control of his phone and made it unusable. 

This was a “Drive-by Download“ attack and due to his oversight, Vivek’s phone was infected with a Malware. 

New Android malware can infect your phone by simply visiting a website Andrord “malware HummingBad infects 10 million phones

Malwares can be a Virus, Worm or Troian horse that can come to you through use of un-licensed software, unknowingly downloading free but untrusted software programs, or through the use of infected pen drives, storage cards etc 

How to be safe? 

1) Never click unfamiliar links or download unfamiliar content. 

2) Keep your computer system updated with a good anti-virus software 

3) ignore any mails or invites which comes from unknown sources. 

4) Always scan the shared drives before using it.


 

read less
Comments
Dislike Bookmark

About UrbanPro

UrbanPro.com helps you to connect with the best BSc Tuition in India. Post Your Requirement today and get connected.

Overview

Lessons 29

Total Shares  

+ Follow 53,777 Followers

Related Topics

Top Contributors

Connect with Expert Tutors & Institutes for BSc Computer Science

x

Ask a Question

Please enter your Question

Please select a Tag

X

Looking for BSc Tuition Classes?

Find best tutors for BSc Tuition Classes by posting a requirement.

  • Post a learning requirement
  • Get customized responses
  • Compare and select the best

Looking for BSc Tuition Classes?

Find best BSc Tuition Classes in your locality on UrbanPro

Post your learning requirement

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 25 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 6.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more