How to use malloc to dynamically allocate memory

Sdílet
Vložit
  • čas přidán 5. 09. 2024
  • Today we look at how to allocate memory using malloc and calloc, and how to manually remove this memory (as it's not cleaned up automatically) using the free function. Feel free to ask questions in the comments below!
    ---
    IDE used in the video: sourceforge.ne...
    Check out my course over on Udemy: www.udemy.com/...

Komentáře • 63

  • @achillesa5894
    @achillesa5894 Před 9 měsíci +12

    This guy just explained this in 7 minutes better than 4 years of university I'm not even kidding

  • @benstone5650
    @benstone5650 Před 2 lety +8

    The best absolute malloc video that I've ever saw! It takes books a full chapter to do what you did in less than 7 minutes.

  • @larsmichael6242
    @larsmichael6242 Před 3 lety +36

    Your videos are making my entrance into programming so easier, keep up the great work!

    • @yahyafati
      @yahyafati Před 2 lety +4

      YOU STARTED WITH C!!! WHAT IS WRONG WITH YOU? YOU ARE A LEGEND

    • @florianreinhardt4689
      @florianreinhardt4689 Před 2 lety +6

      @@yahyafati It's called having a sadistic professor in my case :'D

  • @vasekharang
    @vasekharang Před 27 dny

    You can also access the elements by doing *(p+1) = 34; because p points to first address, if you add one, you will point to second

  • @Gupatik
    @Gupatik Před rokem +1

    I really get amazed every time I see someone who's still working with C or trying to learn it.

    • @CodeVault
      @CodeVault  Před rokem +2

      There are still many schools teaching it. For many it's actually mandatory to learn C for your computer science degree. Whether that's a good thing or not, that's debatable

    • @PanosPitsi
      @PanosPitsi Před rokem

      @@CodeVault I passed the whole web dev course and cant pass the starter c course, sucks. My test is in 2 hours lol

    • @yesh420
      @yesh420 Před 2 dny

      @@PanosPitsi how did it go? lol

    • @PanosPitsi
      @PanosPitsi Před dnem

      @@yesh420 I passed it but then dropped out of the uni. I went to an east London university after that and did great. 💀

  • @joelmanning249
    @joelmanning249 Před 2 lety +7

    Once again a very clear and easy to follow tutorial.

  • @lauraborghijs3168
    @lauraborghijs3168 Před 2 lety +1

    Awesome that I found this video the day before my exam lol, thanks! Great video :)

  • @gman2455
    @gman2455 Před 3 lety +2

    Thanks for the tutorial. Helping me start my C journey

  • @magedal-ward1511
    @magedal-ward1511 Před 2 lety +1

    let me call you "C MASTER"
    thanks man

  • @TheeKariuki-vy4ub
    @TheeKariuki-vy4ub Před 10 měsíci

    A very nice and clear explanation on malloc

  • @agsiar
    @agsiar Před 3 lety +4

    I'm starting to learn C and I have a few questions about arrays, malloc and pointers and hope you could help me clear things up a little:
    1) Is there some sort of problem if I copy an array with something like this:
    int A[5]={1,2,3,4,5};
    int B[sizeof(A)/sizeof(A[0])];
    for (int i=0; i

    • @CodeVault
      @CodeVault  Před 3 lety +8

      1) Not really, that's perfectly fine, but it won't work if you want to pass A to a different function since sizeof(A) would return sizeof(int*) which is usually 8. You can use memcpy without using malloc: memcpy(B, A, sizeof(A)); Relevant video: code-vault.net/lesson/32ec2c63ka:1603733520352
      2) Yes, it is necessary. While there are certain mechanisms in place that clean up this unused memory it is very important you clean your own memory... otherwise your memory footprint will grow unnecessarily. Another thing to consider is if the program is long running then the memory you don't free will be wasted.
      3) Firstly, I am NOT declaring an array in the video. I am declaring a POINTER to the first element of an array. It is an important distinction. Secondly, int p[3]; would define the array statically and not dynamically. I prefer using statically defined array whenever possible but sometimes you do need dynamic memory. Relevant video: code-vault.net/lesson/24fbf25820b420e1e0bb6147e5096e6e
      4) *p = 5 means: set the value AT the address p to 5
      p = 5 means: set the value OF p to 5
      If you do p = 5 then if you dereference that pointer, it will cause a crash simply because you're making the program dereference the value at address 0x0000000000000005 which is reserved for some system functions probably. Relevant video: code-vault.net/lesson/cw3spqag9u:1603733522844 also this little guide could be useful to better understanding pointers: code-vault.net/product/ea173333939c13ed960dea60b2007938

    • @agsiar
      @agsiar Před 3 lety +2

      @@CodeVault Wow! I see that there is a lot that I'm yet to learn. I'll make sure to come back to this comment at a later date when I've studied some more about pointers, dynamic memory allocation and related topics. Thank you very much for your answer! :)

    • @bossman5370
      @bossman5370 Před 2 lety

      @@agsiar hows it going

    • @weeb2006
      @weeb2006 Před 2 lety +1

      im glad u asked this question, I've been trying to find reference for question 1 but couldn't find it anywhere

    • @garybuttherissilent5896
      @garybuttherissilent5896 Před rokem

      @@CodeVault Wow, great answer!

  • @Firebomber03
    @Firebomber03 Před 2 lety

    Ty very much. I will be taking an exam on programming tommorow :)

  • @chudchadanstud
    @chudchadanstud Před 2 lety +4

    No need to free it. Memory leaks are fun

  • @fuffi8550
    @fuffi8550 Před 2 lety +2

    why do i want to cast malloc?

    • @CodeVault
      @CodeVault  Před 2 lety +3

      This is a very old video actually. You don't actually need to do this in C, although it is recommended to cast the return value of malloc in C++

  • @xinking2644
    @xinking2644 Před rokem

    great video, thank you, by the way, nice haircut bro

  • @puripatratanaarpa4066
    @puripatratanaarpa4066 Před 2 lety +1

    Thanks for sharing.

  • @johndunham6791
    @johndunham6791 Před 2 lety

    Excellent video. Thank you.

  • @tomasvenere1670
    @tomasvenere1670 Před 6 lety

    Thanks! That was really clear.
    If you could do some longer video about double pointers and things like that you could be viral :)

  • @Henrix1998
    @Henrix1998 Před 2 lety +1

    2:45 that's not true in operating systems at least. The memory will be freed by the OS when the process exits

  • @kevinklein2562
    @kevinklein2562 Před rokem

    let's say on had malloc in a loop and it iterated along it's array and by the end of the loop the pointer address is near the end of the array. If I wanted to free the entire malloc(ed) memory, how can I do so by pointing back to the beginning of that array?

    • @CodeVault
      @CodeVault  Před rokem

      You'd have to iterate again through that array and call free() on each pointer that you got from using malloc(). The direction of the iteration doesn't matter but you will still need the beginning address as otherwise you wouldn't know where to stop iterating

  • @televisaoassassina9822
    @televisaoassassina9822 Před 2 lety +1

    Hey! I'm trying to move away from scanf and wrote this to get some integers.
    int main(){
    char array[2][9];
    int i;
    for(i=0; i

    • @CodeVault
      @CodeVault  Před 2 lety +1

      I don't think you need malloc for this. You could simply reuse the same string and have an array of integer results:
      char array[9];
      int results[2];
      for (i = 0; i < 2; i++) {
      fgets(array, 9, stdin);
      results[i] = atoi(array);
      }
      // a and b is in the results array

    • @televisaoassassina9822
      @televisaoassassina9822 Před 2 lety

      @@CodeVault ATOI WORKS ON ARRAYS?? Man, the conundrums I get into for not reading function documentation. Thanks a lot!

    • @CodeVault
      @CodeVault  Před 2 lety

      Well, char arrays are strings. So I guess you could say that. I suggest using strtol instead of atoi, it has a few more useful features: code-vault.net/lesson/ppdf96xhwi:1603733526989

  • @incrediblygay
    @incrediblygay Před 2 lety

    Following this tutorial gives me a seg fault when creating a larger pointer array

    • @CodeVault
      @CodeVault  Před 2 lety

      Interesting. How large did you make the array?

  • @smoua4588
    @smoua4588 Před rokem

    Good job.

  • @dowed1209
    @dowed1209 Před rokem

    thanks my top g

  • @DenisovichDev
    @DenisovichDev Před 2 lety

    Thank you

  • @cr.6848
    @cr.6848 Před 3 lety

    Can you help me with a problem ? How can I melloc a struct, more precisely a struct with pointers like char*.. I tried using a malloc but end up getting "interrupted by signal 11". The weird thing is that it works in another project, are they critical points that i need to know when i use malloc on struct ?. I want to use it inside a loop were i malloc some space for data in every loop step, because i use a double linked list for my inputs.

    • @CodeVault
      @CodeVault  Před 3 lety +1

      When you malloc a struct with a char* in it you just allocate space for that pointer (for that address). But you don't actually make that pointer point to anything valid, so you'll probably have to call malloc for that char* too.
      Something like this:
      myStruct* s = malloc(sizeof(myStruct));
      s->c = malloc(sizeof(char) * 100);

    • @cr.6848
      @cr.6848 Před 3 lety

      @@CodeVault ah thank you, that make sense, I will try it

  • @ibrahimbah4234
    @ibrahimbah4234 Před 2 lety

    THX!

  • @panfrog489
    @panfrog489 Před 3 lety

    Thanks

  • @ducduong6328
    @ducduong6328 Před rokem

    how about realloc?

    • @CodeVault
      @CodeVault  Před rokem

      I talk a bit about realloc in this video: code-vault.net/lesson/747ik43y18:1603733522146

  • @ahmedsinger9435
    @ahmedsinger9435 Před 2 lety

    thanks

  • @t_rm2119
    @t_rm2119 Před 3 lety

    just started watching the video, ngl he looks cute
    Edit: Thanks! Good explanation :D

  • @chengpeng9285
    @chengpeng9285 Před 2 lety

    cool

  • @brightray9199
    @brightray9199 Před 3 lety +1

    What were you looking at right time and again?..........lol

    • @CodeVault
      @CodeVault  Před 3 lety +5

      It's where I had my other monitor. I think I had some documentation open there and the recording software but nowadays I try to not do this anymore. It's incredibly distracting

  • @SESINNUMERGE
    @SESINNUMERGE Před 6 lety

    incearca sa nu te mai uiti asa mult spre dreapta, acolo e monitorul sau ai ceva script? e distracting, oricum.

    • @CodeVault
      @CodeVault  Před 6 lety

      Mersi de feedback. Voi incerca sa aplic sfatul tau. Mersi!

  • @ocho3749
    @ocho3749 Před 2 dny

    usually, malloc is pronounced as malloc.
    thank me later 😊

  • @soniablanche5672
    @soniablanche5672 Před 8 měsíci

    isn't malloc in ?

  • @chipdacat
    @chipdacat Před 5 měsíci

    basically how to make an miner program if you loop it (without the free() line)