DOC PREVIEW
UCF COP 3502 - Dynamically Allocated Memory in C

This preview shows page 1-2-3-4-5 out of 15 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 15 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 15 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 15 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 15 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 15 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 15 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Dynamically Allocated Memory in CAll throughout the C course (COP 3223), all examples ofvariable declarations were statically allocated memory. Theword “static” means “not changing” while the word “dynamic”means “changeable,” roughly speaking.In regards to memory, what this means is as follows:(1) static – the memory requirements are known at compile-time. Namely, after a program compiles, we can perfectlypredict how much memory will be needed and when forstatically allocated variables. The input the program mayreceive on different executions of the code will NOT affect howmuch memory is allocated. One serious consequence of this isthat any statically allocated variable can only have its memoryreserved while the function within which it was declared isrunning. For example, if you declare an int x in function A, iffunction A has completed, no memory is reserved to store xanymore.(2) dynamic – the memory requirements are NOT known (forsure) at compile-time. It may be the case that on differentexecutions of the program, different amounts of memory areallocated; thus, the input may affect memory allocation. If you want to allocate memory in one function, and have thatmemory available after the function is completed, you HAVE toallocate memory dynamically in that function!!!Secondly, since dynamically allocated memory isn’t “freed”automatically at the end of the function within which it’sdeclared, this shifts the responsibility of freeing the memory tothe user. This can be done with the free function.malloc, calloc functionsHere are the formal descriptions of the two functions we will typically use to allocate memory dynamically:// Allocates unused space for an object //whose size in bytes is specified by size // and whose value is unspecified, and // returns a pointer to the beginning of the // memory allocated. If the memory can’t be // found, NULL is returned.void *malloc(size_t size);// Allocates an array of size nelem with// each element of size elsize, and returns// a pointer to the beginning of the memory// allocated. The space shall be initialized // to all bits 0. If the memory can't be// found, NULL is returned.void *calloc(size_t nelem, size_t elsize);Although these specifications seem confusing, they basicallysay that you need to tell the function how many bytes toallocate (how you specify this to the two functions is different)and then, if the function successfully finds this memory, apointer to the beginning of the block of memory is returned. Ifunsuccessful, NULL is returned.Dynamically Allocated ArraysSometimes you won't know how big an array you will need fora program until run-time. In these cases, you can dynamicallyallocated space for an array using a pointer. Consider thefollowing program that reads from a file of numbers. We willassume that the first integer in the file stores how manyintegers are in the rest of the file. The program on the following page only reads in all the valuesinto the dynamically allocated array and then print thesevalues out in reverse order.Note that actual parameter passed to the malloc function. Wemust specify the total number of bytes we need for the array.This number is the product of the number of array elementsand the size (in bytes) of each array element. It should be fairly easy to see how we can change the codebelow to utilize calloc instead of malloc. In this particularexample, since there is no need to initialize the whole block ofmemory to 0, there’s no obvious advantage to using calloc. But,when you want to initialize all the memory locations to 0, itmakes sense to use calloc, since this function takes care of thattask.#include <stdio.h>int main() { int *p, size, i; FILE *fp; // Open the input file. fp = fopen("input.txt", "r"); // Read in all the numbers into the array. fscanf(fp, "%d", &size); p = (int *)malloc(size*sizeof(int)); for (i = 0; i<size; i++) fscanf(fp, "%d", &p[i]); // Print out the array elements backwards. for (i = size-1; i>=0; i++) printf("%d\n", p[i]); // Close the file and free memory. free(p); fclose(fp); return 0;}A couple notes about pointers and dynamic arraysThe return type of malloc is void*. This means that the returntype for malloc must be casted to the type of the pointer thatwill be pointing to the allocated memory.The reason for this is so that malloc can be used to allocatememory for all types of structures. If malloc returned an int *,then we couldn't use it to allocate space for a character array,for example.Instead, all malloc does is return a memory location w/o anyspecification as to what is going to be stored in that memory.Thus, the programmer should (the book says it isn't necessary,but the gcc compiler will give you a warning if you don't dothis) cast the return value from malloc to the type they want.All this cast really does is specify the memory to be broken into"chunks" in a particular way. (Once we know what we arepointing to, we know how many contiguous memory locationsstores a piece of data of the array.)Although I haven't specified above, it is possible for malloc tofail to find the necessary memory in the heap. If this occurs,malloc returns NULL. A good programming practice is tocheck for this after each malloc call.I've never had a malloc call fail. But, the potential is there ifyou do NOT free memory when possible. Once you are doneusing a dynamic data structure, use the free function to freethat memory so that it can be used for other purposes.reallocSometimes, what may occur is that an array gets filled, but youwant to "extend" it because more elements must be stored. Based on the method of dynamic memory allocation already discussed, this could be solved in the following manner:1) Allocate new memory larger than the old memory.2) Copy over all the values from the old memory to the new.3) Free the old memory.4) Now we can add new values to the new memory.We can avoid this extra work through a function that does it for us, realloc. void *realloc(void *ptr, size_t size);Here's the description from the IEEE standards web page about this function:The realloc() function shall change the size of the memoryobject pointed


View Full Document

UCF COP 3502 - Dynamically Allocated Memory in C

Download Dynamically Allocated Memory in C
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Dynamically Allocated Memory in C and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Dynamically Allocated Memory in C 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?