第13章ではArraysをDescriptionしました。
This array proves to be a very effective means of handling large amounts of data,
Actually, there are a few drawbacks and it's somewhat impractical.
The main drawback of arrays is that their size cannot be changed within a program.
You can only specify the number of elements with a constant when declaring an array.
It's not possible to prompt the user for input and utilize that value during runtime.
Changeable environment
GCCというCompilerでは独自の拡張により、 The number of elements can be changed within the program. Similarly, this functionality has been added in newer versions of the C language, such as C99.
This makes it inconvenient to create programs that function for various purposes.
For example, if you were to build software to manage a company's employee salaries,
The array to store employee salaries will need to be large enough to accommodate more than the number of employees.
However, companies vary greatly, ranging from those with just a few employees to those with thousands.
If the number of elements is 10, it cannot be used by companies with 11 or more people.
Conversely, if the number of elements is set to 10,000, the remaining 9,990 become wasted in companies with only 10 employees.
"It also consumes memory for this wasted space, resulting in a significant amount of wasted memory."
"In this way, the number of elements in an array cannot be changed freely,"
It's difficult to utilize memory effectively, and it lacks practicality.
Memory allocation
As explained in the preceding paragraph, arrays are inconvenient because their element count cannot be freely changed.
Therefore, a `malloc` function is provided to create arrays freely.
Also, you need to include <stdlib.h> to use the malloc function.
The usage of the malloc function is as follows.
malloc function
Pointer variables = malloc(必要なメモリのバイトサイズ);
The pointer variable returned is assigned the address of the beginning of the allocated array.
You can use it like an array with the [] operator.
I wonder if everything will be alright.
If you don't understand the meaning of the previous three lines, you should reread Chapter 15.
The `malloc` function only accepts sizes specified in bytes.
To allocate an array of arbitrary size, use the `sizeof` operator.
The memory allocated by the malloc function is sometimes referred to as the heap.
It is also sometimes referred to as a dynamic array when an array is allocated in the heap.
In case of memory allocation failure (e.g., due to severe memory shortage), NULL is returned.
"If you use this as is, it will crash."
You must always check the return value of the `malloc` function.
However, we are experiencing severe memory exhaustion and have no immediate solutions.
It depends on the app, but if it returns NULL, I guess there's nothing to do but give up and force-quit.
キーワード
【heap】
A space to store large-sized memory used for extended periods.
Memory allocated by the malloc function persists until the program terminates.
If that memory is no longer needed, it is freed using the free() function.
If you forget to do this, unnecessary memory will continue to remain.
If you use the malloc function, you must always call the free function.
The usage of free functions is as follows.
A pointer variable should be used to store the return value of the malloc function.
The following program dynamically allocates an array of 10 integer elements.
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;
}
"The `sizeof(int)` operator determines the size of a single integer variable in bytes,"
Multiplying it by 10 allocates memory for 10 integer variables.
The address returned by the malloc function is a void pointer.
This type is one that can be assigned to any pointer variable.
Actually, a cast to (int *) isn't necessary.
"You're going to get an error if you don't cast it in the C++ compiler."
If memory allocation fails, the exit function will be called to terminate the program.
The exit function is a function that terminates a program.
Please note that you need to include `` to use the exit function.
By the way, the abort() function can also be used when terminating due to an error.
When you're finished using the allocated array, call the free function to deallocate it.
Expanding the number of elements in a dynamic array.
The malloc function allows you to create dynamic arrays of any size.
However, this prevents changing the number of elements in the array, as initially stated.
I wouldn't say the issue has been completely resolved.
Therefore, there is a function, realloc, available to change the number of elements.
The usage of the realloc function is as follows.
"Previous pointer variables would be assigned the address of memory allocated by the malloc function."
The `realloc` function resizes a memory block while preserving its contents.
The new pointer variable will return the address of the allocated memory.
You can specify the same variable as a previous pointer variable unless there's a specific reason not to.
The following program modifies the number of elements in a dynamic array using the realloc function.
To be honest, that's all I can say about the malloc function.
"It's just that simple: create an array of the necessary size using the malloc function, and free it using the free function when you no longer need it."
However, this is also the biggest problem with C.
If you forget to free the memory allocated with functions like malloc when it's no longer needed,
That memory will remain unused indefinitely, resulting in what's known as a memory leak.
Memory leak
皆さんも、長Timeコンピュータを使っているうちに、 I think you've probably experienced a situation where the system gradually slows down until it needs to be restarted. 実は、あの現象の原因が、まさにfreefunctionの呼び出し忘れなのis. Memory leaks occur when you forget to release dynamically allocated memory.
You've likely heard of the term "memory leak."
Also, if you use your computer or smartphone for a long time without restarting it, it gradually becomes slower.
This phenomenon is something you've likely experienced yourselves.
This is a memory leak, or forgetting to free the memory – forgetting to call the `free` function.
"With simple examples like the ones presented here, it's easy to remember to call the free function."
However, in large-scale or hyper-scale programs, it can turn into a nightmare.
It is extremely difficult to distinguish between memory that is in use and memory that is no longer needed.
In practice, C and its extension, C++, do not provide a smart solution to this problem.
Currently, we are addressing the issue through extensive and thorough testing.
Therefore, in languages like Java, there's a mechanism called garbage collection...
Programming languages with automatic memory deallocation features have emerged and are now widely used.
Garbage collection
A feature that resolves memory leaks by automatically monitoring memory usage. ほとんどのMemory leakをautomatic的に解決してくれるため、 In modern app development, languages that incorporate this functionality are often used.
ただし、メモリの利用効率上のムダが多くなってしまう弱点も抱えています
However, garbage collection inevitably results in a significant amount of overhead.
"A language called Rust has also emerged, which achieves both automatic memory deallocation and efficient memory utilization."
Rust is also one of the most anticipated programming languages right now.
Rust programming language
"This language features an ownership system, providing a fundamental solution to memory leaks." "Simply put, it's a language where programs with memory leaks will result in compilation errors."
メモリの利用効率をまったくムダにすることなく、ほぼ完全なMemory leak対策ができるが、 ちょっとしたミスでもコンパイルできなくなってしまうため、 It's a programming language that can be quite exhausting to program in.
"However, it's undoubtedly the best language currently for addressing memory leak issues." Going forward, many future operating systems and system apps will be developed in Rust.
About This Site
Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.