Malloc Explained in 60 Seconds

Поділитися
Вставка
  • Опубліковано 1 жов 2024
  • Malloc explained in 60seconds

КОМЕНТАРІ • 134

  • @rezamirhosseini1369
    @rezamirhosseini1369 8 місяців тому +346

    Freeing dynamically allocated memory is not good practice. It's REQUIRED.

    • @mananasi_ananas
      @mananasi_ananas 8 місяців тому +25

      No it's not. No one is forcing you to free memory and sometimes there's actually good reasons to not do it. One reason: mallocs are expensive operations. If you want to avoid calling malloc and free too many times, you can malloc a certain size. Then when you're "done" with the memory instead of freeing it, you can cache the pointer to use again at a later time. This avoids a malloc & free call saving time and avoiding memory fragmentation.

    • @rezamirhosseini1369
      @rezamirhosseini1369 7 місяців тому +46

      @@mananasi_ananas You are describing a memory pool: allocate some blocks of memory, use and reuse them to avoid allocate-free cycles, boost performance and avoid memory fragmentation. But you keep track of the pointers to free them when they are not needed. Unless they are needed until program exit.
      In a non-GC language, successive dynamic allocations without freeing them leads to memory leakage and unstable behavior. You must have a strategy for memory management.

    • @mananasi_ananas
      @mananasi_ananas 7 місяців тому +7

      @@rezamirhosseini1369 But still no one is forcing you to free the memory yourself. If the pointers are used until program exit I don't free them. I would say freeing memory is usually good practice, it is not required.

    • @narrativeless404
      @narrativeless404 7 місяців тому +16

      ​@@mananasi_ananas If you'll never use it again, you definitely should free it
      Because if you then allocate it again and do the same thing, you'll cause a memory leak that's going to kill your program at some point

    • @narrativeless404
      @narrativeless404 7 місяців тому +2

      ​@@mananasi_ananasIf they are used though, you should keep track of that until the program exits

  • @MIchaelArlowe
    @MIchaelArlowe 7 місяців тому +76

    Malloc explained in 3 words: “It allocates memory”

    • @yochem9294
      @yochem9294 3 місяці тому +5

      Two words: "allocates memory"

    • @b01abinesh15
      @b01abinesh15 Місяць тому

      ​@@yochem9294 one word malloc

    • @forhadrh
      @forhadrh Місяць тому +3

      one word: malloc

  • @jakubication
    @jakubication Рік тому +90

    you've piqued my curiosity. i've heard and understood freeing the memory when you're done with it in school, but i've never heard about setting the pointer to null.
    is that just "idiot proofing" your code basically so you don't use it again accidentally?

    • @TheBuilder
      @TheBuilder  Рік тому +79

      free doesn't set your pointer to null and you have no idea if the address you point at is still valid so setting it to null makes sure you avoid future confusion

    • @CallousCoder
      @CallousCoder 7 місяців тому +3

      You don’t need to but your null checks would fail if you accidentally would reuse the pointer with desastreus effects.
      I never set them to null if they are in a function that I will return from immediately as I cannot reuse those. But in for example main or a function that still has code after the free I just do it out of habit.
      I also have no idea what the reason is to not set the pointer to 0 either. I can’t see any use for that.

    • @maxaafbackname5562
      @maxaafbackname5562 7 місяців тому +1

      ​@@CallousCoderI think from historical standpoint.
      Not in all cases it is useful to set the variable to NULL.
      (As described in the comments.)
      If it is not necessary, it will not be done (by the std library) to save code space and runtime.
      Both very expensive in that days.
      Additionally you have to pass the address of the pointer as argument to free(). May be adfionsl code in that days with less fancy processirs at caller and/or callee side.

    • @CallousCoder
      @CallousCoder 7 місяців тому +1

      @@maxaafbackname5562 well doing an xor rx, rx and store are 2 small instructions. So I don’t think that was it.

    • @CallousCoder
      @CallousCoder 7 місяців тому

      @@maxaafbackname5562 well doing an xor rx, rx to set the pointer to null, and store are 2 small instructions.
      So I don’t think that was it.
      I think it was more like: “you manage memory so you know that you shouldn’t reuse that pointer.

  • @KyleHarrisonRedacted
    @KyleHarrisonRedacted 7 місяців тому +42

    Explained so eloquently 👌

  • @ohwow2074
    @ohwow2074 Рік тому +96

    It's not a good practice but it's a must. The memory must be freed.

    • @DragonOfInfinity
      @DragonOfInfinity 9 місяців тому +3

      Why is it not a good practice?

    • @ohwow2074
      @ohwow2074 9 місяців тому +34

      @@DragonOfInfinity I mean it's not JUST a good practice but ALSO a must. The only place a program can leave memory there without freeing it is when it is exiting. The OS will claim the process's memory after it exists.

    • @DragonOfInfinity
      @DragonOfInfinity 9 місяців тому +1

      @@ohwow2074 Ah, gotcha! I was already wondering 😅
      Thanks for the quick reply!

    • @krakow10
      @krakow10 8 місяців тому +10

      I think "must" is too strict and "good practice" is too lenient. Your software will run fine with memory leaks until you cumulatively run out of memory so it's not a "must", but if you practice not freeing memory your software development peers will kill you, so it's more than "good practice". Somewhere in between.

    • @HL1_EP1
      @HL1_EP1 8 місяців тому +6

      Any good operating system will likely free the memory after the program has terminated but it's still good practice.

  • @grumpyyellowfang3344
    @grumpyyellowfang3344 9 місяців тому +149

    I'm a computer science student who started with java and python, and my jaw dropped when I saw this. ABSOLUTELY INSANE. I CANNOT BELIEVE MY EYES AT SUCH BRILLIANT MALEVOLENCE CREATED BY THE C GODS. I'm genuinely going insane that this can exist I simply cannot believe my eyes.

    • @grumpyyellowfang3344
      @grumpyyellowfang3344 9 місяців тому

      GONE ARE THE DAYS OF CREATING AN ARRAY OF SET SIZE, GONE ARE THOSE DAYS

    • @glitchy_weasel
      @glitchy_weasel 8 місяців тому +55

      It is not that it _can_ exist, it's that it _must_ exist. With how low level the C language is, malloc is likely implemented just on top of the memory management functionality provided by the operating system.
      Every other more modern language boils down to doing this internally.

    • @FourOf92000
      @FourOf92000 8 місяців тому +19

      welcome to memory management, it builds what you run on

    • @CallousCoder
      @CallousCoder 7 місяців тому +15

      Don’t they start with C and then assembly anymore in college? These were some of the first things after basic control flow that
      we were taught. But then again I didn’t study CS but Micro electronics, so perhaps that’s the difference.
      Also I found the concept of malloc rather useless as one of the first C lessons and in combination of microcontrollers because it’s a libc thing and mostly when you do embedded development on tiny systems you don’t want the libc as it’s pretty big and you own all the memory to start with because there’s no OS (usually) to request memory from. So you just managed it all yourself. Aaah those good ole days, when the first thing you did when writing a demo or a game was to disable the operating system to get full control to everything.

    • @narrativeless404
      @narrativeless404 7 місяців тому

      Java and Python are absolutely no fit for a first contact with the programming world
      You should know about C/C++ and Assembly first

  • @dl_supertroll
    @dl_supertroll 7 місяців тому +5

    Pointers, assembly
    Manage your memory with malloc() and free()

    • @afraid2letgo
      @afraid2letgo 5 місяців тому

      Program in C!
      Program in C!

  • @erikkonstas
    @erikkonstas 7 місяців тому +14

    0:20 In C++ we usually do not do manual memory management... well Systems Programming is the exception, but for instance if you need mmap() you don't use malloc().
    0:35 Actually, a slight (advanced-level) nitpick there: multiplication can overflow! The size_t type is just another unsigned type, and you typically expect the contract that "malloc() returns truthy pointer == enough memory has been found", so an overflow is both possible and a huge nuisance (it can result in buffer overflow). This is especially true for the common case where you have a length and an element size for an array you want to allocate, and you naively go and multiply them to get the total size, while in reality potential overflow should be checked against (and, if it would happen, allocation must fail because the very definition of size_t implies there can't be enough memory in such a case).
    1:00 Using free() when it's time to is not just "good practice"; since C does not include a GC (it would defeat the efficiency of native executables), not freeing memory in time causes a memory leak.

    • @Cd5ssmffan
      @Cd5ssmffan 7 місяців тому +4

      what do u expect from ppl making youtube tutorials based on 20 yr old standards xdddd

    • @erikkonstas
      @erikkonstas 7 місяців тому +5

      @@Cd5ssmffan The standard ain't at no fault there... the whole "60 seconds" shebang is.

    • @TheBuilder
      @TheBuilder  7 місяців тому +4

      The latest standard for C is coming out in a few months

    • @James-l5s7k
      @James-l5s7k 15 днів тому

      Good catch on the multiplication overflow. Always good practice to check that the number is

    • @James-l5s7k
      @James-l5s7k 15 днів тому

      @@Cd5ssmffan I thought it was great!

  • @BigJMC
    @BigJMC 3 місяці тому +2

    “With great power comes great responsibility”

  • @tokuumeiii8792
    @tokuumeiii8792 5 місяців тому +4

    short n rich , thank u✔✔

  • @muhammadfaizan1700
    @muhammadfaizan1700 7 місяців тому +7

    Nice! Good Explained in a short time ❤

    • @TheBuilder
      @TheBuilder  7 місяців тому

      Glad it was helpful!

  • @CXLVII
    @CXLVII Рік тому +12

    I did enjoy the video and I will watch more.

  • @etzbert
    @etzbert 7 місяців тому +3

    yes, C u later :)

  • @TheForge47
    @TheForge47 Рік тому +19

    int **matrix = (int **) malloc(ROWS * sizeof(int *));
    for(int i = 0; i < ROWS; i++) {
    matrix[ i ] = (int *) malloc (COLS * sizeof(int));
    }
    Good old days 😂

    • @TheBuilder
      @TheBuilder  Рік тому +10

      okay, i want to go back to C++ now

    • @TheForge47
      @TheForge47 Рік тому +8

      @@TheBuilder 😜 yeah modern c++ is a difference like day and night. Especially with the introduction of stl 🤯

    • @ohwow2074
      @ohwow2074 Рік тому +5

      You forgot to free those arrays ☠️

    • @abhiranjansinha5565
      @abhiranjansinha5565 8 місяців тому +4

      for (int i = 0; i < ROWS; ++i)
      free(matrix[i]);
      free(matrix);
      matrix = NULL;
      This should work :)

    • @glitchy_weasel
      @glitchy_weasel 8 місяців тому +4

      From Stack Overflow, you can also apparently do:
      int (*arr)[M] = malloc(sizeof(int[N][M]));
      Which makes arr a pointer to an int[M]. That way you avoid the double indirection when accessing an element.

  • @dehrk9024
    @dehrk9024 6 місяців тому +2

    i love malog

  • @justinadrowski38
    @justinadrowski38 7 місяців тому +1

    I don’t get what it means when it says allocates the bytes

    • @TheBuilder
      @TheBuilder  7 місяців тому

      It means it gives you an address to memory you have to clean up later

    • @RoadToFuture007
      @RoadToFuture007 4 місяці тому +1

      It means it gives you an address to a chunk of memory of a size you have ordered which is now free for you to use (you can write into it to store some data in it etc) but after you no longer need this data you have to release it bu using free(pointer_returned_from_malloc). Maybe you are confused why you have to allocate some memory at all if you can simply declare a variable like: x = 2;
      Yes you can do this and this is called automatic memory allocation which is happening on the stack memory. In this case you don't need to hassle with malloc() and pointers. But the problem with it is that when you don't know before or during the compilation time how much memory you will need for a certain data you need to allocate memory dynamically (meaning during the runtime of your program) which is happening on the heap and is done with the help of malloc(). This is called dynamic memory allocation and in this case you have to work with pointers and stuff. And also you have to free this memory wen you are done.

  • @jeeperyeepr236
    @jeeperyeepr236 6 місяців тому

    this was really good but i can hear all your mouth noises and breathe ins.

  • @pgpython
    @pgpython 4 місяці тому

    An important point about malloc is the data isn't initialiased in anyway so it could contain random data. You should always initialize the data after allocating it.
    If you are allocating strings. You have to allocate one more byte than the size of the string you want to allocate and set the last byte allocated to null.
    Also if you want to change the size of the block you allocated, there is realloc, again you have to check for null

  • @johnjosephlonergan
    @johnjosephlonergan 4 місяці тому

    More interesting what happening behind the scenes

  • @christosbinos8467
    @christosbinos8467 5 місяців тому

    What about allocation of memory when I don't know the number of data points? For example, storing user input in an array, say an integer array, in the case where I don't know how many integers the user will pass.

    • @TheBuilder
      @TheBuilder  5 місяців тому +2

      the easiest method would be to sip the input using getchar to read one character at a time and resize as you run out of memory.

    • @christosbinos8467
      @christosbinos8467 2 місяці тому

      @@TheBuilder Thanks :)
      Since then, I have progressed significantly with my understanding of C, and this is no longer a problem.

  • @japaneselearner3405
    @japaneselearner3405 4 місяці тому

    Great programming pill

  • @dedotikea
    @dedotikea 7 місяців тому

    Love the explanation. Subscribed👌

  • @mirkovbranislav1290
    @mirkovbranislav1290 8 місяців тому

    other way around in 0:22

    • @erikkonstas
      @erikkonstas 7 місяців тому +1

      No...? C++ is the one which doesn't have auto cast between non-void and void pointer. But, as I said in another comment, malloc() in C++ is not common anyway.

  • @gregorymorse8423
    @gregorymorse8423 7 місяців тому +3

    Didnt even talk about memory framentation or page sizes. Epic fail.

  • @blocks4857
    @blocks4857 7 місяців тому

    This is my favorite c++ feature heart 😍 😍😍😍😍

  • @ZephyrCheez
    @ZephyrCheez 8 місяців тому

    I've literally never found low level memory management to be difficult. Idk what people are complaining about

    • @TheBuilder
      @TheBuilder  8 місяців тому +3

      It's not difficult, but it adds cognitive load

    • @rezamirhosseini1369
      @rezamirhosseini1369 7 місяців тому +1

      @@TheBuilder And it's error-prone.

    • @narrativeless404
      @narrativeless404 7 місяців тому

      It's not difficult, unless the code is enormous and unreadable
      The operation itself isn't hard. The management is. It's kinda hard to keep track of numerous pointers to memory you've allocated prior

    • @RoadToFuture007
      @RoadToFuture007 4 місяці тому

      Well I also thought it is easy. I even wrapped all my C-style object constructors and destructors so that they keep track of of pointers and inside the destructors I do free() and ptr=NULL and STILL my program crashes ://