MMGames Introduction to C C Language Development Environment C language now Useful Apps Contact Us
MMGames

Automatic version identification

SpineViewer

It's easy to tell by looking at it.

Response Time Checker

I can leave my computer on and do it.

Mouse cleaning time

I can leave my computer on and do it.

Mouse cleaning time

C language learned by suffering
C language learned by suffering

Create arrays at will

Array drawbacks
Chapter 13 explained how to use arrays.
This array is a very effective means of handling large amounts of data, but
In fact, there are several drawbacks that make it somewhat impractical.

The biggest drawback of arrays is that the number of elements cannot be changed in the program.
The only way to do this is to directly specify the number of elements as a constant when declaring the array.
It is not possible to have the user enter a value during execution and use that value.

Environment that can be changed
The compiler, GCC, has its own extensions to the
The number of elements can be changed in the program.
A similar feature has also been added in the newer C language, C99.

This is inconvenient for programs that operate for a variety of purposes.
For example, if you are creating software to manage the salaries of your company's employees
The array to store employee salaries must be larger than the number of employees.

However, there is a wide range of companies in the world, from those with a few employees to those with several thousand.
If the number of elements is set to 10, it cannot be used in a company with more than 11 employees, and
Conversely, if the number of elements is set to 10,000, the remaining 9,990 elements are wasted in a company with 10 employees.
Since memory is also used for this waste, it is a huge waste of memory.

Thus, since the number of array elements cannot be changed at will, the
It is difficult to use memory effectively and lacks practicality.
Memory allocation
In the previous section, we explained that arrays are inconvenient because the number of elements cannot be freely changed.
For this reason, the malloc function is provided to create arrays at will.
Note that you must #include <stdlib.h> to use the malloc function.
The usage of the malloc function is as follows

malloc function
 Pointer variable = malloc(byte size of memory needed);

The returned pointer variable is assigned the first address of the allocated array.
Using the [] operator, it can be used in the same way as an array.

I hope it's okay.
If you don't know what the above three lines mean, re-read chapter 15.

Since the malloc function can only specify the size in bytes, the
To allocate an array of any number of elements, use the sizeof operator.
The memory allocated by the malloc function is sometimes called a heap.
Arrays allocated in the heap are sometimes called dynamic arrays.

Note that NULL is returned if memory allocation fails (e.g., due to severe memory shortage).
Using it as it is will result in a forced termination.
The return value of the malloc function must always be checked.

However, there is a serious memory shortage situation and there is no countermeasure for this.
It depends on the application, but if NULL is returned, I think the only thing to do is to give up and force termination.

Keywords.
Heap]

An area that stores a large size of memory used over a long period of time.



Keywords.
Dynamic array

The malloc function, for example, can be used to
An array of any size prepared during program execution.


The memory allocated by the malloc function remains until the program terminates, but the
When that memory is no longer needed, it is released using the free function.
If you forget to do this, you will be left with wasted memory.
Always call the free function after using the malloc function.
The usage of the free function is as follows

malloc function
 free(pointer variable);


Free function on exit
We have explained that the free function is always called, but there are exceptions.
Just before the program terminates, the free function does not have to be used.
The OS releases memory as soon as the program terminates.
However, the free function should always be called.

Specify a pointer variable that contains the return value of the malloc function.

The following program dynamically allocates an array of 10 elements of type int.

Source Code
 #include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int* heap;
    heap = (int*)malloc(sizeof(int) * 10);
    if (heap == NULL) exit(0);

    for (i = 0; i < 10; i++) {
        heap[i] = i;
    }

    printf("%d\n", heap[5]);

    free(heap);

    return 0;
}

Since sizeof(int) determines the size in bytes of a single variable of type int, the
By multiplying it by 10, memory is allocated for 10 int-type variables.

The address returned by the malloc function is a pointer of type void.
Since this type says that it can be assigned to any pointer variable
You don't really need to cast it to (int *), but
The C++ compiler will give an error if you do not cast.

If memory allocation fails, the exit function is called to force termination.
The exit function terminates the program.
Note that you must #include <stdlib.h> to use the exit function.
Incidentally, the abort function may also be used in case of forced termination due to an error.

When finished using the allocated array, call the free function to release it.

Actual state of the malloc function
The malloc function allows you to create dynamic arrays of any size you want.
Although very convenient, the mechanism is actually just marking memory.

This is akin to putting your name on a piece of candy in the fridge.
If everyone in the family follows the name and doesn't eat other people's snacks, there is no problem.
There is a good chance that the candy could be eaten by others due to a misunderstanding.

The malloc function has similar properties and is surprisingly difficult to use well.
Therefore, when programming, try to use regular arrays as much as possible, and
It is better to use the malloc function only where it is absolutely necessary.

Expanding the number of elements in a dynamic array
The malloc function can be used to create a dynamic array of any number of elements.
However, this does not allow us to change the number of elements in the array, which we mentioned at the beginning.
This is not to say that the problem has been completely solved.
Therefore, a realloc function is provided to change the number of elements.
The usage of the realloc function is as follows

realloc function
 New pointer variable = realloc(previous pointer variable, byte size of memory needed);

The previous pointer variable is the address of memory allocated by the malloc function.
The realloc function allocates memory of the new size while preserving the contents.
The new pointer variable returns the address of the extended memory, but
Unless there is a special reason not to, you can specify the same variable as the previous pointer variable.

The following program changes the number of elements in a dynamic array with the realloc function.

realloc function
 #include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int* heap;
    heap = (int*)malloc(sizeof(int) * 10);
    heap = (int*)realloc(heap, sizeof(int) * 100);
    free(heap);
    return 0;
}

The realloc function increases the number of elements from 10 to 100.

Let's reduce the number of calls.
If the realloc function is called too many times, memory becomes cluttered.
This condition is called fragmentation and can lead to instability.
It is recommended to reserve a certain amount of memory in the initial malloc function, and to use a larger amount in the realloc function.
When calling the realloc function, you should allocate a larger amount at a time.

Fighting memory leaks
As a matter of fact, this is all there is to explain about the malloc function.
The malloc function creates an array of the required size, and when it is no longer needed, the free function releases it, and that's it.
But this is also the biggest problem of the C language.

If you forget to free the dynamic memory (the array created by the malloc function) with the free function when you no longer need it
The memory will remain unused for a long time, resulting in a so-called memory leak.

memory leak
I'm sure you've all spent a lot of time on your computer.
You may have experienced that it gradually slows down and you have to reboot the system.
In fact, the cause of this phenomenon is precisely the forgetting to call the free function.
Forgetting to free dynamic memory is called a memory leak.


Readers have probably heard the word "memory leak" before.
Also, if you use your computer or phone for a long time without rebooting it, it gets slower and slower.
You have probably experienced this phenomenon before.
This is a forgetting to free dynamic memory, i.e., a forgetting to call the free function.

In a simple example such as the one presented here, it is easy to remember to call the free function.
However, in large or very large programs, it can turn around and become a nightmarishly difficult task.
It is extremely difficult to distinguish between memory that is being used and memory that is no longer needed.

In effect, the C language and its extension, the C++ language, do not smartly solve this problem, and
The current situation is somehow being countered by extensive and thorough testing.

Therefore, it is important to use garbage collection, such as in the Java language, which is a
Programming languages with the ability to automatically free memory have emerged and are widely used.

garbage collection
The function resolves memory leaks by automatically monitoring the memory being used.
Because it automatically resolves most memory leaks, the
Modern application development increasingly uses languages with this functionality.

However, it also has the weakness of increasing waste in terms of memory usage efficiency.

However, because garbage collection is inevitably wasteful, the
The Rust language, which allows both automatic memory release and efficient use of memory, has also emerged.
The Rust language is also the most promising programming language in the market today.

Rust Language
The ownership system provides a fundamental countermeasure against memory leaks in this language.
Very crudely put, "A program that leaks memory is a compile error" language.

It is an almost perfect solution to memory leaks without wasting any memory usage efficiency, but it is not a perfect solution to memory leaks.
Even a small mistake can cause it to fail to compile.
It is a programming language that is quite tiring to write programs.

However, it is definitely the best language at the moment for dealing with the memory leak problem.
It is likely that many future OS and system applications will be developed in Rust.



About this Site

The C language (bitter C), which is learned by suffering, is
This is the definitive C language introductory site.
It systematically explains the basic functions of the C language and
It is as complete as or more complete than any book on the market.

Part 0: Program Overview
  1. What is the program?
Chapter 2: How to write a program
  1. Writing Rules
  2. Writing conventions
  3. Exercise 2
Chapter 3: Display on Screen
  1. String display
  2. newline character
  3. Exercise 3
Chapter 4: Numeric Display and Calculation
  1. Numeric Display
  2. Basic Calculations
  3. Type of value
  4. Exercise 4
Chapter 5: Numerical Memory and Calculation
  1. Memorize values
  2. Variable Type
  3. Type conversion
  4. Numeric justification
  5. Exercise 5
Chapter 6: Input from the keyboard
  1. Functions for input
  2. Fear of Input
  3. Exercise 6
Chapter 9: Repetition with a fixed number of times
  1. Sentences that repeat themselves
  2. Loop Operation Mechanism
  3. Exercise 9
Chapter 10: Unknown number of repetitions
  1. Loop of unknown frequency
  2. input check
  3. Exercise 10
Chapter 13: Handling Multiple Variables at Once
  1. Multiple variables are handled together.
  2. How to use arrays
  3. Exercise 13
Chapter 19: Dynamic Arrays
  1. Create arrays at will
  2. Exercise 19
Chapter 20: Multiple Source Files
  1. Minimal division
  2. The Stone of Partition
  3. Exercise 20

Comment
COMMENT

Open the 💬 comment submission box