Sams Teach Yourself C in 24 Hours (48 page)

BOOK: Sams Teach Yourself C in 24 Hours
2.53Mb size Format: txt, pdf, ePub
ads

size specifies the total byte number you want to change to. The realloc() function returns a void pointer.

The realloc() function returns a null pointer if it fails to reallocate a piece of memory

,

space.

The realloc() function is equivalent to the malloc() function if the first argument passed to realloc() is NULL. In other words, the following two statements are equivalent: ptr_flt = realloc(NULL, 10 * sizeof(float));

ptr_flt = malloc(10 * sizeof(float));

22 067231861x CH17 1/25/00 10:19 AM Page 289

Allocating Memory

289

Also, you can use the realloc() function in place of the free() function. You do this by passing 0 to realloc() as its second argument. For instance, to release a block of memory pointed to by a pointer ptr, you can either call the free() function like this: free(ptr);

or use the realloc() function in the following way:

realloc(ptr, 0);

The program in Listing 17.4 demonstrates the use of the realloc() function in memory reallocation.

TYPE

LISTING 17.4

Using the realloc() Function

1: /* 17L04.c: Using the realloc() function */

17

2: #include

3: #include

4: #include

5: /* function declaration */

6: void StrCopy(char *str1, char *str2);

7: /* main() function */

8: main()

9: {

10: char *str[4] = {“There’s music in the sighing of a reed;”,

11: “There’s music in the gushing of a rill;”,

12: “There’s music in all things if men had ears;”,

13: “There earth is but an echo of the spheres.\n”

14: };

15: char *ptr;

16: int i;

17:

18: int termination = 0;

19:

20: ptr = malloc((strlen(str[0]) + 1) * sizeof(char));

21: if (ptr == NULL){

22: printf(“malloc() failed.\n”);

23: termination = 1;

24: }

25: else{

26: StrCopy(str[0], ptr);

27: printf(“%s\n”, ptr);

28: for (i=1; i<4; i++){

29: ptr = realloc(ptr, (strlen(str[i]) + 1) * sizeof(char));

30: if (ptr == NULL){

31: printf(“realloc() failed.\n”);

32: termination = 1;

continues

22 067231861x CH17 1/25/00 10:19 AM Page 290

290

Hour 17

LISTING 17.4

continued

33: i = 4; /* break the fro loop */

34: }

35: else{

36: StrCopy(str[i], ptr);

37: printf(“%s\n”, ptr);

38: }

39: }

40: }

41: free(ptr);

42: return termination;

43: }

44: /* funciton definition */

45: void StrCopy(char *str1, char *str2)

46: {

47: int i;

48:

49: for (i=0; str1[i]; i++)

50: str2[i] = str1[i];

51: str2[i] = ‘\0’;

52: }

The following output is obtained by running the executable program 17L04.exe.

There’s music in the sighing of a reed;

OUTPUT
There’s music in the gushing of a rill;

There’s music in all things if men had ears;

There earth is but an echo of the spheres.

The purpose of the program in Listing 17.4 is to allocate a block of memory
ANALYSIS
space to hold a character string. There are four strings in this example, and the length of each string may vary. I use the realloc() function to adjust the size of the previously allocated memory so it can hold a new string.

As you can see in lines 10–13, there are four character strings containing a lovely poem written by Lord Byron. (You can tell that I love Byron’s poems.) Here I use an array of pointers, str, to refer to the strings.

A piece of memory space is first allocated by calling the malloc() function in line 20.

The size of the memory space is determined by the (strlen(str[0])+1)*sizeof(char) expression. As mentioned earlier, because the C function strlen() does not count the null character at the end of a string, you have to remember to allocate space for one more character to hold the full size of a string. The sizeof(char) expression is used here for portability, although the char data type is 1 byte.

22 067231861x CH17 1/25/00 10:19 AM Page 291

Allocating Memory

291

Exercise 4 at the end of this lesson asks you to rewrite the program in Listing 17.4 and replace the malloc() and free() functions with their equivalent formats of the realloc() function.

If the malloc() function doesn’t fail, the content of the first string pointed to by the str[0] pointer is copied to the block of memory allocated by malloc(). To do this, a function called StrCopy() is called in line 26. Lines 45–52 give the definition of StrCopy().

The for loop, in lines 28–39, copies the remaining three strings, one at a time, to the block of memory pointed to by ptr. Each time, the realloc() function is called in line 29 to reallocate and adjust the previously allocated memory space based on the length of the next string whose content is about to be copied to the memory block.

After the content of a string is copied to the memory block, the content is also printed
17

out (see lines 27 and 37).

In this example, a block of memory space is allocated and adjusted based on the length of each of the four strings. The realloc() function, as well as the malloc() function, does the memory allocation and adjustment dynamically.

Summary

In this lesson you’ve learned the following very important functions and concepts for memory management in C:

• In C, there are four functions that can be used to allocate, reallocate, or release a block of memory space dynamically at runtime.

• The malloc() function allocates a block of memory whose size is specified by the argument passed to the function.

• The free() function is used to free up a block of memory space previously allocated by the malloc(), calloc(), or realloc() function.

• The calloc() function can do the same job as the malloc() function. In addition, the calloc() function can initialize the allocated memory space to 0.

• The realloc() function is used to reallocate a block of memory that has been allocated by the malloc() or calloc() function.

• If a null pointer is passed to the realloc() function as its first argument, the function acts like the malloc() function.

• If the second argument of the realloc() function is set to 0, the realloc() function is equivalent to the free() function that releases a block of allocated memory.

22 067231861x CH17 1/25/00 10:19 AM Page 292

292

Hour 17

• You have to first include the header file stdlib.h before you can call the malloc(), calloc(), realloc(), or free() function.

• You should always check the values returned from the malloc(), calloc(), or realloc() function, before you use the memory allocated by these functions.

In the next lesson you’ll learn more about data types in C.

Q&A

Q Why do you need to allocate memory at runtime?

A
Very often, you don’t know exact sizes of arrays until your program is being run.

You might be able to estimate the sizes for those arrays, but if you make those arrays too big, you waste the memory. On the other hand, if you make those arrays too small, you’re going to lose data. The best way is to allocate blocks of memory dynamically and precisely for those arrays when their sizes are determined at runtime. There are four C library functions, malloc(), calloc(), realloc(), and free(), which you can use for memory allocation at runtime.

Q What does it mean if the
malloc()
function returns a null pointer?

A
If the malloc() function returns a null pointer, it means the function failed to allocate a block of memory whose size is specified by the argument passed to the function. Normally, the failure of the malloc() function is caused by the fact that there is not enough memory left to allocate. You should always check the value returned by the malloc() function to make sure that the function has succeeded before you attempt to use the block of memory allocated by the function.

Q What are the differences between the
calloc()
and
malloc()
functions?

A
Basically, there are two differences between the calloc() and malloc() functions, although both functions can do the same job. The first difference is that the calloc() function takes two arguments, while the malloc() function takes only one.

The second difference is that the calloc() function initializes the allocated memory space to 0, whereas there is no such guarantee made by the malloc() function.

Q Is the
free()
function necessary?

A
Yes. The free() function is very necessary, and you should use it to free up allocated memory blocks as soon as you don’t need them. As you know, memory is a limited resource in a computer. Your program shouldn’t take too much memory space when it allocates blocks of memory. One way to reduce the size of memory taken by your program is to use the free() function to release the unused allocated memory in time.

22 067231861x CH17 1/25/00 10:19 AM Page 293

Allocating Memory

293

Workshop

To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix B, “Answers to Quiz Questions and Exercises.”

Quiz

1. Provided that the char data type is 1 byte, the int data type is 2 bytes, and the float data type is 4 bytes, how many bytes of memory do the following functions try to allocate?

• malloc(100 * sizeof(int))

• calloc(200, sizeof(char))

17

• realloc(NULL, 50 * sizeof(float))

• realloc(ptr, 0)

2. Given an int pointer, ptr, that is pointing to a block of memory that can hold 100

integers, if you want to reallocate the memory block to hold up to 150 integers, which of the two following statements do you use?

• ptr = realloc(ptr, 50 * sizeof(int));

• ptr = realloc(ptr, 150 * sizeof(int));

3. After the following statements are executed successfully, what is the final size of the allocated memory block pointed to by the ptr pointer?

. . .

ptr = malloc(300 * sizeof(int));

. . .

ptr = realloc(ptr, 500 * sizeof(int));

. . .

ptr = realloc(ptr, 60 * sizeof(int));

4. What is the final size of the allocated memory block pointed to by the ptr pointer, if the following statements are executed successfully?

. . .

ptr = calloc(100 * sizeof(char));

. . .

free(ptr);

ptr = realloc(NULL, 200 * sizeof(char));

. . .

ptr = realloc(ptr, 0);

22 067231861x CH17 1/25/00 10:19 AM Page 294

294

Hour 17

Exercises

1. Write a program to ask the user to enter the total number of bytes he or she wants to allocate. Then, initialize the allocated memory with consecutive integers, starting from 1. Add all the integers contained by the memory block and print out the final result on the screen.

2. Write a program that allocates a block of memory space to hold 100 items of the float data type by calling the calloc() function. Then, reallocate the block of memory in order to hold 50 more items of the float data type.

3. Write a program to ask the user to enter the total number of float data. Then use the calloc() and malloc() functions to allocate two memory blocks with the same size specified by the number, and print out the initial values of the two memory blocks.

4. Rewrite the program in Listing 17.4. This time, use the two special cases of the realloc() function to replace the malloc() and free() functions.

23 067231861x CH18 1/25/00 10:31 AM Page 295

HOUR 18

Using Special Data Types

and Functions

That’s all there is, there isn’t any more.

—E. Barrymore

In Hour 4, “Understanding Data Types and Keywords,” you learned about

most of the data types, such as char, int, float, and double. In Hour 15,

“Working with Functions,” you learned the basics of using functions in C. In this hour, you’ll learn more about data types and functions from the following topics:

• The enum data type

• The typedef statement

• Function recursion

• Command-line arguments

23 067231861x CH18 1/25/00 10:31 AM Page 296

296

Hour 18

The
enum
Data Type

BOOK: Sams Teach Yourself C in 24 Hours
2.53Mb size Format: txt, pdf, ePub
ads

Other books

The Other Crowd by Alex Archer
Promises Kept by Scarlett Dunn
01 - Murder at Ashgrove House by Margaret Addison
Beyond Repair by Kelly Lincoln
The Roper (Rodeo Nights) by Moore, Fancy
The Stanforth Secrets by Jo Beverley
The Fortunate Brother by Donna Morrissey