3.creating a dynamic structure in c using malloc( )

Опубликовано: 18 Апрель 2017
на канале: DASARI TUTS
21,919
143

The C function malloc is the means of implementing dynamic memory allocation. It is defined in stdlib.h or malloc.h, depending on what operating system you may be using. Malloc.h contains only the definitions for the memory allocation functions and not the rest of the other functions defined in stdlib.h. Usually you will not need to be so specific in your program, and if both are supported, you should use "stdlib.h", since that is ANSI C, and what we will use here.

The corresponding call to release allocated memory back to the operating system is free.

When dynamically allocated memory is no longer needed, free should be called to release it back to the memory pool. Overwriting a pointer that points to dynamically allocated memory can result in that data becoming inaccessible. If this happens frequently, eventually the operating system will no longer be able to allocate more memory for the process. Once the process exits, the operating system is able to free all dynamically allocated memory associated with the process.

Recall array can be considered a pointer which we use as an array. We specify the length of this array is 10 ints. After array[0], nine other integers have space to be stored consecutively.

Sometimes it is not known at the time the program is written how much memory will be needed for some data. In this case we would want to dynamically allocate required memory after the program has started executing. To do this we only need to declare a pointer, and invoke malloc when we wish to make space for the elements in our array, or, we can tell malloc to make space when we first initialize the array. Either way is acceptable and useful.

We also need to know how much an int takes up in memory in order to make room for it; fortunately this is not difficult, we can use C's builtin sizeof operator. For example, if sizeof(int) yields 4, then one int takes up 4 bytes. Naturally, 2*sizeof(int) is how much memory we need for 2 ints, and so on.


Смотрите видео 3.creating a dynamic structure in c using malloc( ) онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь DASARI TUTS 18 Апрель 2017, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 21,91 раз и оно понравилось 14 людям.