But what if there is a requirement to change this length size. For Example, If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory in this array.
So there is a requirement to lessen the length size of the array from 9 to 5. Take another situation. In this, there is an array of 9 elements with all 9 indices filled. But there is a need to enter 3 more elements in this array. In this case, 3 indices more are required. So the length size of the array needs to be changed from 9 to This procedure is referred to as Dynamic Memory Allocation in C. Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure like Array is changed during the runtime.
C provides some functions to achieve these tasks. They are:. It returns a pointer of type void which can be cast into a pointer of any form. And, the pointer ptr holds the address of the first byte in the allocated memory. If space is insufficient, allocation fails and returns a NULL pointer. It has two parameters or arguments as compare to malloc. The memory allocated using functions malloc and calloc is not de-allocated on their own.
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Skip to content. Change Language. Related Articles. Table of Contents. Save Article. Improve Article. Like Article. You ask where the actual phone is and they look confused and say "I've given you a number, isn't that all you need? Take-home point Every phone has a phone number but merely having a number does not magically create a phone at the end of it!
You don't know Fred's phone number, so you open up your phone's address book and make an entry for Fred with a random, made-up phone number: You dial Fred in your phone - he picks up!
Take-home point It's not enough to have an entry for Fred in our contact list, it must also contain Fred's correct phone number. In order to dereference a pointer it is absolutely essential that its value has been explicitly set to the address of a legitimate variable, just as when we dial a phone number it is essential that it is the number of the correct telephone.
C has a special value called NULL which it can be guaranteed no legitimate pointer will ever have. We've seen this already: fopen returns NULL if the open of a file failed, and in general, any function that returns a pointer to something useful will return NULL when it fails, and that should always be checked for.
Using a value of NULL by mistake is not safe but it is probably less dangerous than using any other value. The symptoms of pointer errors are the same as those of giving a random index to an array and for exactly the same reason: we are trying to access a random memory location. Initialising pointers to NULL improves the chance of this happening which is why we recommend it. If we are unlucky, a pointer error will cause our program to behave randomly.
Putting in printf statements to debug may cause the problem to go away So far we have used "ordinary" arrays, declared inside functions. We've been able to assign the addresses of the first element of these arrays to pointers, nearly always in a separate function, and to then use these pointers to access this array using the familiar syntax p[i].
This requires us to know the sizes of our arrays we will need when we write the program, or at the very least soon after the program starts but often the sizes of arrays, or number of items we need to store, will change as the program progresses.
For example, a word-processor will have new paragraphs added or removed and a web browser will display new pages or tabs. In a scientific context we may need to wish to use an adaptive mesh whose resolution changes as the program progresses. To allow for situations where the amount of memory required changes as the program progresses , it is possible to dynamically allocate memory as we need it. In particular we can dynamically allocate anonymous arrays which can then be used like any other memory such as that obtained by declaring arrays.
We can also get rid of them when we are finished with them. Dynamically allocated memory acts as an anonymous nameless arrays which we can create and destroy and with care grow and shrink at will. If we do it right we can then use pointername [j] just like any other block of memory. A failed attempt To see why we need a specific function to do this allocation let's see what happens when we try to do this by calling an ordinary function with a local array and returning the address of this array:.
Can you work out what the problem is? What will happen to farray when badArrayAlloc returns? The problem with the above code is that farray vanishes when badArrayAlloc returns and ar becomes a "dangling pointer": it is pointing to something that no longer exists.
Have you ever had the situation where you have phoned somebody only to find they have changed their phone number without telling you? If so, this was an example of a "dangling phone number"! It accepts the number of bytes required as an argument, allocates some previously unused memory and returns the address of this memory to the calling function.
If the function assigns this to a point p then we can use p[0] , p[1] etc just like a pointer to any other array. C also provides a handy operator sizeof which tells us the number of bytes need to store an object. Step through the above "Key example". To illustrate the use of malloc and the value it returns. Step through the above "Key example" in a new window.
Now click until malloc is called. Notice how an new array of N floats comes into existence with the usual random values.
Unlike every other array we have seen before, this one has no name! So we just refer to it by its address.
Now click once more and notice that the value of p is the address of the first element of the anonymous array. Notice too that the anonymous array has not disappeared when malloc returned. Now go through the rest of the code. Pause at the first assignment to p[i] inside the for loop ie the assignment of p[0]. Check you understand why this means the first element of the array. Carry on for the assignment of p[1] etc.
It's the ideal argument to malloc! There's also a version sizeof float which is less useful. Neither evaluates the thing it operates on.
When stepping through the example we see that the allocated memory has an address and that the value of the pointer p is that address. We therefore use p to access this memory. We have to do it this way as memory allocated in this way is anonymous, it has no name to refer to it by. Allocated memory must have an address which can be reached from the value of a variable, otherwise we cannot access it and it gets "lost".
The malloc function is unusual in that although it obtains some memory it never needs to use it. It does not care if the calling function wants to use it store an array of int s, float s or anything else. The argument to malloc must be some sort of integer and that integer must be able to be large enough for the largest amount of memory malloc can return. We will use these pieces of information below.
We must always check that malloc did not return NULL. We have met the exit function before, does pretty much what it says and by convention, successful programs exit with zero.
0コメント