Create arrays freely.
Drawbacks of arrays
Chapter 13 explained how to use arrays.
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.
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.
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
The GCC compiler, through its own extensions, allows the number of
elements to be changed within the program. Additionally, similar functionality has been added in C99, a newer version of the C language.
elements to be changed within the program. Additionally, similar functionality has been added in C99, a newer version of the C language.
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.
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.
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.
A space to store large-sized memory used for extended periods.
An array of arbitrary size prepared during program execution using functions such as malloc.
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.
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.
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 variable = malloc(required memory size in bytes);
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.
Keyword
【heap】
A space to store large-sized memory used for extended periods.
Keyword
【Dynamic array】
An array of arbitrary size prepared during program execution using functions such as malloc.
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.
malloc function
free(Pointer variable);
Free function at exit
Although I explained that the free function must always be called, there are exceptions. Just before the program terminates, the OS will release the memory automatically when the program ends, even if you don't use the free function. However, make it a habit to always call the free function.
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 `
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.
The Reality of the malloc Function
The malloc function is extremely convenient because it allows you to create dynamic arrays of any size as you please. However, its mechanism is essentially just marking memory.
This is similar to writing names on snacks stored in the refrigerator. As long as everyone in the family follows those names and avoids eating others' snacks, there's no problem. But there's always the possibility that someone might mistakenly eat someone else's snack.
The malloc function shares similar characteristics, making it surprisingly difficult to use effectively.
Therefore, when programming, it's best to use regular arrays whenever possible,
reserving the malloc function only for absolutely necessary parts.
This is similar to writing names on snacks stored in the refrigerator. As long as everyone in the family follows those names and avoids eating others' snacks, there's no problem. But there's always the possibility that someone might mistakenly eat someone else's snack.
The malloc function shares similar characteristics, making it surprisingly difficult to use effectively.
Therefore, when programming, it's best to use regular arrays whenever possible,
reserving the malloc function only for absolutely necessary parts.
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.
The realloc function is being used to increase the number of elements from 10 to 100.
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.
realloc function
New pointer variable = realloc(previous pointer variable, required memory size in bytes);
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.
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 is being used to increase the number of elements from 10 to 100.
Let's reduce the number of calls.
Calling the realloc function multiple times leads to memory fragmentation. This condition is called fragmentation and causes instability. You should allocate a sufficiently large amount initially with the malloc function, and when calling realloc, allocate a larger amount in a single call.
The Battle Against Memory Leaks
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 the C language.
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.
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.
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.
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 the C language.
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
I'm sure many of you have experienced your computer gradually slowing down after prolonged use, eventually forcing a restart. The cause of that phenomenon is precisely forgetting to call the free function. Forgetting to release dynamically allocated memory is called a memory leak.
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 automatically resolves memory leaks by monitoring used memory.
Since it automatically resolves most memory leaks,
modern app development increasingly uses languages equipped with this feature.
However, it also has the weakness of increasing waste in memory utilization efficiency.
Since it automatically resolves most memory leaks,
modern app development increasingly uses languages equipped with this feature.
However, it also has the weakness of increasing waste in memory utilization efficiency.
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
A language that fundamentally addresses memory leaks through its ownership system.
Put very simply, it's a language where programs that leak memory will fail to compile.
It enables nearly complete protection against memory leaks without wasting any memory efficiency,
but even minor mistakes prevent compilation,
making it a programming language that is quite exhausting to write programs in.
However, it is undoubtedly the most effective language for addressing memory leak issues at present.
Future operating systems and system applications will likely be developed increasingly in Rust.
Put very simply, it's a language where programs that leak memory will fail to compile.
It enables nearly complete protection against memory leaks without wasting any memory efficiency,
but even minor mistakes prevent compilation,
making it a programming language that is quite exhausting to write programs in.
However, it is undoubtedly the most effective language for addressing memory leak issues at present.
Future operating systems and system applications will likely be developed increasingly in Rust.
About This Site
Learning C language through suffering (Kushi C) isThis 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.




