int *y = malloc(100);

Can someone explain line Nr (9) and what is malloc function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16



#include <stdio.h>
#include <stdlib.h>
  
int main(void) {
  int x = 3;
  int *y = malloc(100);
  printf("x is at : %p\n", &x);
  printf("y is at : %p\n", y);
  x = y[1000];
  printf("x is : %d\n", x);
  return 0;
}
Last edited on
Do you know what "the heap" is?

That code has multiple memory errors. If you're luck it'll crash, if not it'll keep going to the end giving you the impression that all's well.
I know the heap is part of memory is used for dynamically allocated and it stores globales and classes unlike the stack , but how can this help me to understand the line number 9?
L9 obtains 100 bytes of memory from the heap and assigns the address of the first to y. The memory is not initialised.

https://en.cppreference.com/w/c/memory/malloc

There a few different areas of memory, where the C/C++ virtual machine is concerned.
1. Global and static variables are held in a "data" segment and a initialized to zero.
2. Local variables and function return addresses are held in "the stack".
3. The Heap is a free section of memory that programs can request blocks of memory from.

When you add an extra 16Gbytes of RAM to your computer, that's available in the heap.

You request memory from the heap by calling malloc(), and give it back with free(). If there's nothing to give, malloc() returns NULL, and you're expected to check for that and deal with it.

Asking for 100 bytes with malloc(100), then asking for the value at offset 1000, y[1000], is a serious error and is called a buffer overflow.
Last edited on
if you care, this is C code. C++ usually uses new instead of malloc. C++ may use malloc, and sometimes will because it has the 'realloc' function (and lesser but also usefull calloc) which are not matched anywhere in c++ (you can do the tasks but its more than 1 function call in c++).
Registered users can post here. Sign in or register to post.