malloc function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

malloc function

#include<stdio.h> #include<stdlib.h> int main(){ int *a = malloc(3 * sizeof(*a)); *a = 1; *(a + 1) = 2; *(a + 2) = 3; *(a + 3) = 4; return 0; } What if I allocate 12 bytes of memory (3 ints) and use it until *(a + 3) without using realloc()? I have tasted to run it, and it works. Is it good to do it? What's the problem?

24th Sep 2020, 5:03 PM
Tha Rath Rbt
Tha Rath Rbt - avatar
1 Answer
+ 5
The malloc function allocates a single memory block of the requested size (if possible) and gives a pointer to the beginning of the block. The programmer must free memory in the code on his own. Or it will be released when the program process ends. In addition, here 12 bytes are allocated by the code, and 16 are used ... code line: *( a + 3 ) = 4; it is very bad practice and overshoot of the allocated memory block. This may not lead to a runtime error, but it will damage the memory of some other variables in the program memory. and it is better to allocate memory based on the size of the type, and not depending on the size of the value by pointer ... int *a = (int*)malloc( 3 * sizeof( int ) );
24th Sep 2020, 10:45 PM
Michail Getmanskiy
Michail Getmanskiy - avatar