C 库函数

     

More than a third word of the alphabet, C is a strictly compiled programming language that forms the base of all other languages in the programming world today. In other words, the programs written in C run only after being compiled. C is constrained lớn certain parameters or functions but contains some different functions that serve some specific purpose. In this article, you would be learning about memset() in C & other factors & use cases associated with it.

Bạn đang xem: C 库函数

What is memset()?

The function memset("memory setter") is a standard library function in C language that sets or fills a memory block semantically with a value.

For instance, consider that you have an array of 8 characters consuming 8 bytes of memory when this array is declared, your computer chunks off 8 bytes of memory on the heap available in your system. This memory allocation is not random. Randomization occurs only when the process like Address Space Layout Randomization occurs for some exemplary purposes or, hexadecimal allocation of address in the range of 0x00 khổng lồ 0x07. Consider you declare an array of array of 8 characters as shown.


char array<8>;
*

Initially, you are completely unaware of the contents of this block memory taken by the array without initializing the array. Although it can be nothing but can be an old value that you might have used in the previous programs, or the block in the memory might be undefined.

In general, và to keep up with good practices while working with C, it is best khổng lồ gain full control over any memory used in any given program. Therefore, instead of leaving these 8 bytes of memory vacant, you must always set or fill the memory with a known or given value along with a null byte (). In this way, you can ensure full control of the memory block consumed by the array defined by you. See the image below lớn get a visual of what is being discussed.

*

In other words, all you want is to lớn memset the functional blocks of memory. The memset() takes the following parameters. The function accepts three parameters, a pointer khổng lồ the block of memory và an integer followed by a size_t which is nothing but an unsigned integer variable designed to hold any index of an array.


void *s, int c, size_t

The first parameter represents a pointer of type void since the memory block is initially empty or about khổng lồ be filled. The type void signifies the pointer can reference the memory regardless of type.

The second parameter is the integer to lớn fill with the pointer allocation. Note that this parameter is received as an integer argument that later gets converted to the character when memory filling is required. This conversion ensures that functions keep only 8 bits needed from the integer parameter. Else it might consume more memory than needed.

The third parameter represents the given form size of the memory block that has khổng lồ be filled. When the pointer references the memory location to lớn fill this space, it tells nothing about how much memory it should fill. Therefore, the main purpose of passing this parameter is to lớn ensure proper and positive kích thước so that memory allocation doesn"t suffer memory loss.

Return value of memset()

The mặc định return value of memset() is void * (pointer with no return type). You might receive nothing back from the memset() if you expect khổng lồ get what you gave khổng lồ these functions. You might only expect lớn get some output đầu ra after the function turns around và returns a pointer with the same memory address passed when you try to điện thoại tư vấn the memset function.

Xem thêm: Vai Trò, Ý Nghĩa Của Chế Biến Thực Phẩm Có Vai Trò Gì ? Chế Biến Thực Phẩm Là Gì

How to use memset()?

To use memset() in your program, the first thing you need to vì is to lớn include the string header tệp tin in your program, as shown below.


#include

Once the string library of C is included in your program, you need nothing more. You can easily access the memset function directly. Khổng lồ make it clearer & easy, consider the below code snippet containing two other libraries like and (for the usage of exit & printf purposes).


#include #include #include int main(void) char memory<8>; /* Fill the memory block with null bytes */ memset(memory, "", 8); printf("%s", memory); /* Fill the memory block with hashes */ memset(memory, "#", 8); printf("%s", memory); /* Fill the memory block with dollar signs */ memset(memory, "$", 8); printf("%s", memory); return (EXIT_SUCCESS);

When is memset() used?

As previously discussed, while programming in C, it is always a best practice to lớn have tight control & maintenance of memory while allocating memory and initializing it. In case you don"t initialize immediately, other dedicated functions like strcpy might come into use. Proper usage of strcpy involves a new block memory allocation method where a copy of a string is kept aside before actually using it. Since it is not initialized, it might need lớn be declared first before actually using strcpy. In such cases, memset() is very suitable lớn fill the block or clear them out initially. Consider the example given below to understand why is memset() used.


#include #include #include int main(void) char src<7> = "Source"; char dest<7>; /* Initialize dest with null bytes for good practice */ memset(dest, "", sizeof(dest)); /* Before copying */ printf("String src before copy: %s", src); printf("String dest before copy: %s", dest); /* Copy src into dest */ strcpy(dest, src); /* After copying */ printf("String src after copy: %s", src); printf("String dest after copy: %s", dest); return (EXIT_SUCCESS);

In general, memset() is a great tool to lớn be considered while working with C và memory allocation methods. In simple words, if you can"t initialize it, memset it.

Applications of memset()

So far, you have lớn see all the relevant examples và use cases for a particular memset() instance. But, lớn understand better, you need khổng lồ look at multiple examples that will be discussed as an application of memset. Consider the below examples that describes its applications.

Example 1


#include #include int main() char a<> = "Hello from JournalDev"; printf("a = %s ", a); printf("Filling the first 5 characters a with "H" using memset "); memset(a, "H", 5 * sizeof(char)); printf("After memset, a = %s ", a); return 0;

Output:


a = Hello from JournalDevFilling the first five characters a with "H" using memsetAfter memset, a = HHHHH from JournalDev
It is quite clear from the previous as well as this example how memset() handles initialization. In the code given above, you can see how memset acts with the variable defining the kích thước of the character array or string. After using the memset() function, you see five repeated characters of H from the given string.

Example 2


#include #include int main() char a<> = "Hello from JournalDev"; printf("a = %s ", a); printf("Filling the last 5 characters a with "H" using memset "); size_t a_len = strlen(a); //Using an offset of (a + a_len - 5), so that we can //fill the last 5 characters memset(a + (a_len - 5), "H", 5 * sizeof(char)); printf("After memset, a = %s ", a); return 0;

Output:


a = Hello from JournalDevFilling the last five characters a with "H" using memsetAfter memset, a = Hello from JournHHHHH
This example is similar khổng lồ the previous one with a catchy hook. It is important to understand the variations of the same programs with different usage techniques of memset(). In the above example, you can see that only the offset location is being filled. In this example, the only difference is the last five characters filled with H since you can see that the memory location or initialization of address has already been done.

Memset() vs calloc() vs naive iteration

There are times when you can opt to use memset() lớn zero for array initialization. Often, there exists some performance issues of other functions like naive approaches or using calloc() function. There are also some tốc độ issues & memory allocation techniques that are hard lớn understand and implement. Lớn understand how memset solves these kinds of problems, see the below example code khổng lồ find why memset() is beneficial lớn use và how both memset() & calloc() can run on a Linux machine using the header file.


#include #include #include #include void* init_with_memset(int* arr, size_t num_locations) // Perform zero initialization with memset // on an integer array return memset(arr, 0, num_locations * sizeof(int)); void* init_with_calloc(int* arr, size_t num_locations) arr = calloc(num_locations, sizeof(int)); return arr; void* init_with_iteration(int* arr, size_t num_locations) { // Naive unoptimized iteration using array indexing for (int i=0; i

Output:


Time for memset() = 0.000002 secondsTime for calloc() = 0.000005 secondsTime for naive iteration = 0.000006 seconds
In the above example, you can easily observe & understand that memset() is thrice as fast as both the native iteration & calloc(). It is so fast because it is already optimized based on the architecture provided by the C compiler, the tốc độ is automatically enhanced.

Xem thêm: Giáo Án Phát Triển Ngôn Ngữ Truyện Quả Bầu Tiên, Giáo Án Phát Triển Ngôn Ngữ

Conclusion

As popularly said, when you don"t initialize, memset it. This proverb usually talks about the advantage of memset over other approaches lượt thích calloc() or native iteration. In this article, you saw how to khuyễn mãi giảm giá with such issues while initializing an array when the space is vacant or unused. The problems and solutions you find in this article tell you how memset can be an important aspect while dealing with memory allocation with a programming language like C.