Dynamic Memory Allocation - CS50 Shorts

Поделиться
HTML-код
  • Опубликовано: 11 дек 2024

Комментарии • 92

  • @mollyexten4508
    @mollyexten4508 4 года назад +63

    The visual walkthrough at the end of this video was really helpful for understanding malloc and dereferencing. Thank you!

    • @FlowersByIrene
      @FlowersByIrene Год назад

      Agreed, I wish I watched this before doing the same exercise in the section.

    • @Duck-9900
      @Duck-9900 5 месяцев назад

      No problem

  • @ytubeleo
    @ytubeleo 4 года назад +60

    Additionally: You have to be very careful with dynamic memory when you don't have much memory available because it can be difficult to work out how much will be available at different parts of your program. Imagine a microcontroller with only 512 bytes of memory! It's common for embedded software companies to ban the use of dynamic memory in such microcontrollers because it is so easy to run out of memory and so hard to predict or fix problems. (In many situations the software design can be changed to use statically-assigned memory instead.)
    This video also doesn't mention that as you malloc() and free() memory it will tend to get fragmented. If you then ask for a big chunk of memory it may not be able to find a contiguous block on the heap. (Contiguous means next to each other, like continuous.) In that case malloc() will return null but you could have more than half your memory technically available/unused. After malloc() returns null, you could then try requesting smaller chunks and managing having your data in different places.
    It's also worth mentioning that modern languages usually use a "garbage collector" (e.g., in Java, Python, Dart) that will automatically free the memory for you when it works out that you no-longer need it. However, these languages usually don't have pointers and instead rely on other techniques.

    • @gonzalozabaleta5338
      @gonzalozabaleta5338 4 года назад +2

      Hi! Thanks for the info. Regarding your last paragraph: does that mean that these concepts of dynamic memory allocation or even Pointers are useless for languages like Java and Python?

    • @ytubeleo
      @ytubeleo 4 года назад +21

      @@gonzalozabaleta5338 Overall it's very useful to know how dynamic memory works. With garbage collection it is basically just calling delete automatically and doing other optimisations for you. When you create an array or a new object in Java or Python it will still have to allocate the memory dynamically (unless it worked out in advance that it could be allocated statically at the start of your program, such as an array that will always get created at the start of your program). And if you increase the size of the array or object after you make it then it'll have to find somewhere to store the extra dynamically. It may be fortunate to have space right after it in memory but will often store it elsewhere without the program even needing to know.
      The part about remembering to delete dynamically allocated variables/objects/memory - and make sure you only delete them once - doesn't apply to languages that manage memory for you and don't have the equivalent of a free/delete command.
      I know that some garbage-collected languages, in particular C#, allow you to also manage memory manually but it's rare (maybe even very very rare) for programmers to want to do that.
      Basically, modern languages are very good at automatically managing the memory - and, along with an advanced operating system, will even write data temporarily to disk for you in a pagefile rather than crashing when you run out. It has become very difficult for programmers to write memory management that works significantly better for their specific program.
      Sometimes you will find that critical parts of a program are written in C or C++ to improve performance whilst the rest is written in a language that programmers can learn and program in faster.
      Low-power embedded systems are a whole other story, especially when you have very limited memory and don't even have an operating system, or the operating system is very basic and doesn't manage memory. In these circumstances it's often critical to avoid any delays. Automatic memory management can introduce unpredictable delays - not great if your airbag deploys 100 ms later because garbage collection was happening!

    • @ytubeleo
      @ytubeleo 4 года назад +18

      In terms of pointers, languages such as Java, Python, Dart, JavaScript, etc., don't use pointers as numbers at all - e.g., you can't add 4 (which means 4 bytes) onto a pointer's address to get the next number in an array of 32-Bit integers.
      However, pointers in C are mainly used for "passing by reference" when you call a function. This allows a function to directly change the original variables or data structures without the function actually returning anything. This is especially useful when you want to change several variables or data structures within one function call, since in C (and many other languages) you can only return one thing from a function.
      Without pointers you would have to return an array or data structure with all the new values and then split out the values and assign them one by one.
      In a language with objects (which C does not have), you can at least store many values in one object (like a struct in C) and give the object one or more "methods" (which are its own personal functions) that can operate on the values within the object and update the object itself - rather than using a normal function like you have to in C and passing it all the values it needs.
      The ability to pass by reference varies by language but few modern languages truly support it. It's powerful and efficient but can cause problems and make code harder to follow and debug. You can easily change the original data when you didn't want to - for example, if there is no option to pass by value instead of pass by reference.
      Java, Dart and JavaScript pass primitive variables by value but for objects pass a reference to the object. (Passing a reference to the object is actually technically different from passing the object itself by reference - you can only change the properties, methods, etc., of the object, not reassign the object to being a whole new object - but don't worry about that for now!)
      Python passes "by assignment" but I believe the result is basically the same as for Java, etc., depending on whether the specific argument is considered "mutable" in the Python language. In short, I think most objects are passed similarly to passing a reference to the object whilst integers, strings, etc., are passed as if by value, like in JavaScript.
      If you search online you will find very long discussions that will hurt your head with people arguing over terminology and philosophy. All that really matters when you are learning is to know whether a function changes the original variable in your current programming language, and that is very easy to test.

    • @DragonRazor9283
      @DragonRazor9283 3 года назад +1

      @@ytubeleo Just ran into your comments and just gotta thank you for the additional insights. It really puts into perspective just how high level of a language Python is and how it does so much work for you (it is my first language!).

    • @farazahmed3373
      @farazahmed3373 2 года назад

      @@ytubeleo God bless you,
      After reading your comments , i can fully absorb the information in this video.

  • @LuaneCarolineAquinoCavalcanti
    @LuaneCarolineAquinoCavalcanti 6 лет назад +20

    This video totally clarified the concepts of heap and stack. I thought they was separated chunks of memory, but actually they just differ in the usage (static or dynamic) of memory.

  • @rahulkumarroy03
    @rahulkumarroy03 6 лет назад +158

    *cough *cough chrome....thanks for this video ♥️

    • @preritvishal
      @preritvishal 4 года назад +36

      You forgot to initialise the pointer *cough to NULL

    • @LifeRacerMe
      @LifeRacerMe 3 года назад +1

      Now I understand the reason of why chrome is a memory hog

    • @andyalberts6621
      @andyalberts6621 Год назад +1

      i was wondering how far I'd have to scroll to see this

  • @br3ak_
    @br3ak_ 3 года назад +6

    Perfect explanation. I, however, don't ever see myself practically using this knowledge in my career as a web developer. I am taking CS50 to better myself as a programmer, these particularities of C just come along with it.

  • @Ragnorok79
    @Ragnorok79 5 лет назад +44

    Everything was explained in the video really well, but I have one important question: What is the point of Dynamically Allocating Memory? Why would it be beneficial for us to allocate memory dynamically versus statically?

    • @elyorbekibrokhimov6754
      @elyorbekibrokhimov6754 5 лет назад +99

      You will gain control over memory without wasting it if you can handle it properly. It will be greatly benfecial when you work with large data enabling your program work faster.
      Let's say you want to get numbers from user input and store them in array of integers. If you don't know exactly how many numbers to be stored, then you would create an array with greatest possible size. However, the actual numbers may be less than size of the array you created. Then unused memory is just garbage that you can't use. But with dynamic allocation you don't have to create the possible greatest value. You can just allocate a memory while your program is running.

    • @osmirog1936
      @osmirog1936 4 года назад +5

      @@elyorbekibrokhimov6754 Makes sense, thank you!

    • @BenGarman
      @BenGarman 4 года назад +4

      @@elyorbekibrokhimov6754 really helpful explanation, thanks

    • @ThePratyushkr23
      @ThePratyushkr23 4 года назад +1

      @@elyorbekibrokhimov6754 thanks

    • @ogurec113
      @ogurec113 4 года назад +1

      @@elyorbekibrokhimov6754 Thank you, it's very helpful!

  • @hamzamuric
    @hamzamuric 6 лет назад +6

    Thanks for making this short videos.

  • @nothjg
    @nothjg 4 года назад +1

    thanks sir you are one of the best teacher i watced pointers , time complexity and few other basic video i fully understand the concept thanks alot

  • @leo_la_rocque
    @leo_la_rocque 5 месяцев назад

    Thanks Mr. Lloyd!

  • @Foreverstudio0192
    @Foreverstudio0192 3 года назад +2

    This tutorial is so good!

  • @wilhelmbauruch
    @wilhelmbauruch 29 дней назад

    Let's just say that if Doug was Michelangelo, this must be his Sistine Chapel. My man is on fire in this class. Great explanation, really appreciate how easy to grasp this concept was after this video.

  • @jeffbowyer4576
    @jeffbowyer4576 4 года назад +7

    On your judgment day, St. Peter will say:
    [booming voice] "Doug Lloyd! Why did you never display "#include " on any of the slides in this video? Why did you spell it out vocally instead?"
    Just a heads up. Be prepared.

  • @nervous711
    @nervous711 3 года назад +5

    Just curious, can anyone explain what will exactly happen if you free the mallocked more than once?

  • @oteikwufrancis1108
    @oteikwufrancis1108 Год назад

    '..browsers that shall remain nameless..' that part cracked me up a bit 😅

  • @BryceChudomelka
    @BryceChudomelka 4 года назад

    Wonderful. Thanks Doug

  • @sduffxlr1549
    @sduffxlr1549 4 года назад +1

    Amazing video, thank you.

  • @martinder3199
    @martinder3199 4 года назад +3

    Alright, nice explanation of what malloc() does, but I don´t understand why it is called dynamic memory allocation? Functionally "a" points to a "box" of memory, so does "b". The only difference I see is that the memory for "a" lives on the stack and the memory for "b" on the heap, but why does that matter?

  • @Firnila
    @Firnila 4 года назад

    Thank you, Doug.

  • @xtalll6297
    @xtalll6297 4 года назад +6

    7:15 lol

  • @opay1234
    @opay1234 5 лет назад

    thank you so much... love this explanation!

  • @arunkumaralagarsamy716
    @arunkumaralagarsamy716 4 года назад +6

    Chrome 😂😂😂the browser which don't free the allocated memory makes the system slow & crash 😂

  • @freelance-writer
    @freelance-writer 4 месяца назад

    Now I understand why I see so much "chrome" when I press Ctrl+Shift+Esc. :)

  • @GOODBOY-vt1cf
    @GOODBOY-vt1cf 4 года назад +1

    thank teacher!

  • @random-xl3zm
    @random-xl3zm Год назад

    amazing !!!!!! very useful

  • @monkeylight8546
    @monkeylight8546 4 года назад +2

    4:36 Why is it written int (star)px instead of int(star) px?
    (Notice the spacing between the two)

    • @joseville
      @joseville 4 года назад +5

      It's down to preference. They are equivalent.

    • @dputra
      @dputra 4 года назад +2

      I'll just drop a link to one of my favorite argument about this sites.google.com/site/jdsarodeprogramming/pointer-concepts/difference-between-int-x-and-int-x-in-c

  • @techfreak416
    @techfreak416 4 года назад +6

    is he talking about chrome??

  • @vandanasonkar1214
    @vandanasonkar1214 4 года назад +2

    Which browser?
    Sir, WHICH BROWSER?

  • @waelchokri1742
    @waelchokri1742 10 месяцев назад

    9:48 للفهم

  • @crististaci9364
    @crististaci9364 3 года назад

    Thank you loyd

  • @UnKnown-lp9gl
    @UnKnown-lp9gl 3 года назад +1

    Pls help me out...
    As said in the video, if we allocate required memory during run time...then Wt is the difference... whether it's during compilation or DMA...we must know it's approx. Size right... except free() function which frees the memory...wt is the point of using DMA? Well, realloc serves a purpose cz, unlike in arrays...we can change i.e., increase size as per our requirement during runtime which is pretty useful...but wt about malloc or calloc?

  • @GhostDocs
    @GhostDocs 3 года назад

    ok i want to know the name of that browser

  • @anonymousani5052
    @anonymousani5052 Год назад

    7:25 he was referring to internet explorer, right?

  • @NKLGaming01
    @NKLGaming01 Месяц назад

    thiss is good, poiter short too

  • @jainamkhakhra3898
    @jainamkhakhra3898 6 лет назад

    Thank you!!

  • @ktswjp
    @ktswjp 4 года назад

    12:00 So you have to go through code to find out if b is passing value or reference. It sounds buggy as hell!

    • @ytubeleo
      @ytubeleo 4 года назад

      It's generally not a problem unless you have no idea what the variable is (in which case you're going to have to look at code or comments elsewhere anyway). If it's not number or a single char then you know it's a pointer / being passed by reference. (Char arrays and Structs are basically just a pointer.)
      In the function arguments/parameter list you have to say whether it is a pointer or a value. And if it's a pointer you will always have to clearly dereference it before using its value.
      You could say the same for any type of variable - "var1" could be a char, int, double, character array, struct, and you have to check out other code to know. Pointer names are very often prefixed with "p" - e.g., "pBalance".
      You could say that it would be useful for C to force you to mark pointers - for example they could begin with "$". However, C is so flexible that you can recast a variable as a different type so that could cause issues too.
      If you really wanted to confuse others you could cast your pointer as an integer, pass it as a value, cast it back into a pointer and dereference it, but that would be deliberately causing problems.
      One thing, however, is that whenever you pass by reference (in any language, I believe), you don't know if the function changes the variable or object you are passing, whereas you do know that if you pass something by value then it of course isn't changing the original object. But that's not unique to C.

    • @ninesquared81
      @ninesquared81 3 года назад

      C is _always*_ call by value. Any argument passed to any function will be copied locally and any changes made in the callee function will not be reflected in the caller function.
      If a function takes a pointer, then the value of the _pointer_ is copied locally (i.e. a pointer is made which points to the same location as the one passed to the function, but the data at that location is not copied). If the function takes a pointer to a non-const value, then it likely edits the data that the pointer points to.
      So edit_string(char *s) likely edits the string s, whereas read_string(const char *s) likely only reads the string, and in fact cannot edit it.
      *If a function receives an array, instead of the entire array being copied to the local scope, the variable inside the function is a pointer to the first element of the array. This means that the array can be edited from within the function (unless it has const elements).

  • @my0wn0p1n10n
    @my0wn0p1n10n 5 лет назад +1

    4:11 shouldn't it be int* px, I'm new to C, so not sure.

    • @enisarik6002
      @enisarik6002 4 года назад

      I think they are the same..

    • @shahman1
      @shahman1 4 года назад +11

      the position of the * does not matter
      int*px;
      int *px;
      int* px;
      int * px;
      they are all the same

    • @helioobianchi
      @helioobianchi 4 года назад +2

      @@shahman1 just to be more explicit:
      when declaring a pointer, the position of '*' does matter: it has to be between the type and the name of the pointer. what don't matter are the spaces between the type and the name

  • @mortalkombat334
    @mortalkombat334 2 года назад

    perfect.

  • @lichitv1164
    @lichitv1164 4 года назад +1

    i think safari app only malloc and forgot to free memory back to me.

  • @puturnamehere777
    @puturnamehere777 4 года назад +1

    Hi Doug, if b is a pointer variable, don’t pointer variables take up space in of themselves inside the computer’s memory? If so, why, at the very end of the video, when you say a = b; do pointer a and pointer b both point to the nameless box? Shouldn’t a point to the location in memory of the pointer variable b? Thanks Doug!

    • @sailokeshkalva8984
      @sailokeshkalva8984 4 года назад +4

      b contains the address of the memory allocated. So a = b assigns the address of the allocated memory to a.

    • @CH3LS3A
      @CH3LS3A 4 года назад +2

      i had the same question, and sai lokesh kalva explains it well. when you assign a = b, remember that you're assigning the variable's values, and b's value is a pointer. therefore a becomes a pointer.

    • @nimrobebo
      @nimrobebo 4 года назад

      @@sailokeshkalva8984 i have a question (might be stupid, but it's confusing me): If we read expressions like a = b from right to left, why then does the pointer a take the address contained by b and not the other way around? I was expecting both a and b to point to int m, rather than to the empty dynamically allocated int box...

  • @Jack_______oh
    @Jack_______oh 2 года назад

    I could be mistaken but I recall in the lectures the notation free;
    Are there situations where you don't need to specify what you are freeing?

  • @wilhelmhofener9893
    @wilhelmhofener9893 4 года назад

    2:32 "pound including"??

  • @edward3105
    @edward3105 4 года назад

    So when you dereferencing u actually go to that adress and manipulate the data that u find into that variable,what is referencing then? i didnt understand??

  • @jjwesker1061
    @jjwesker1061 3 года назад

    Harvard coming up clutch for my upcoming CS1 (Computer Science 1, UCF) Exam?! WOT?

  • @abdelaziz2788
    @abdelaziz2788 5 лет назад

    great!!!!

  • @abdelaziz2788
    @abdelaziz2788 5 лет назад

    anyone have link of the slides ? :(

  • @leee5487
    @leee5487 3 года назад

    Shouldn't it be free(*b)? Is this just a designer flaw or am I misunderstanding the logic?

    • @mtarik0
      @mtarik0 2 года назад

      The computer is smart enough to understand that it's the variable that should be freed. No need to use the dereference operator here, hence.

  • @ali51717
    @ali51717 4 года назад +2

    What's the difference between statically and dynamically declaring a variable?

    • @ytubeleo
      @ytubeleo 4 года назад +6

      That is basically what the whole video is about - watch it again.

  • @kaliomar5988
    @kaliomar5988 5 лет назад

    Hi Mr. Doug,
    as you said in the end of the video when i try to use the freed memory, it does not unpredictable it show me a normal result, i predict some abnormal results but this what happen i appreciate if you explain it to me.
    this is my code:
    int main(void)
    {
    int m;
    m = 10;
    int *a;
    int *b = malloc(sizeof(int));
    a = &m;
    a = b;
    m = 10;
    *b = m+2;
    free(b);
    *a = 11;
    printf("%i
    ",*b);
    }

    • @damian_smith
      @damian_smith 4 года назад +4

      I think (not an expert!) that the computer doesn't necessarily do anything to that memory. If you read it again very quickly, it's unlikely to have changed.
      If you changed your code to wait for a keypress after freeing b, then left it in a terminal window for the rest of the day while you used the computer for other things, and then pressed your key to allow it to keep running, the computer may have put something else in that memory location, or may have allocated it to another application leading to a segfault.

    • @stevefranzreb856
      @stevefranzreb856 4 года назад +1

      @@damian_smith I am also not an expert (that's why I'm here!), but I think Doug basically explained this when he said that even after free()ing b, the pointers still exist and do point to that specific chunk of memory. So, yes, like you said, the computer doesn't necessarily DO anything with that memory, it just allows it to be used elsewhere if needed, like you said if you use your computer for other stuff in the meantime. I think this may be analogous to when you delete something from your hard drive, the information is still there and can be recovered if done quickly enough, but if you save something else to your computer, it may decide to use that old space for the new item. Then the deleted item is unrecoverable.

  • @joseville
    @joseville 4 года назад

    I have a question about stack_array and heap_array if someone knows: us.edstem.org/courses/176/discussion/83181.

  • @GOODBOY-vt1cf
    @GOODBOY-vt1cf 4 года назад

    7:20

  • @LSFprepper
    @LSFprepper 4 года назад +1

    run free(bird) !!!

  • @denniswachira4204
    @denniswachira4204 4 года назад +1

    Haha he is definitely talking about chrome browser

  • @SoySasha
    @SoySasha 4 года назад

    The amount of comments get lower and lower with each video I watch.

  • @fbubbar
    @fbubbar 4 года назад +7

    Did anyone else check their playback speed?