zowiezijdemans
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Week 1 - Memory ## Team Team name: D&Z Date:2022-02-09 Members Zowie Zijdemans Dilawar Faiz | Role | Name | |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------| | **Facilitator** keeps track of time, assigns tasks and makes sure all the group members are heard and that decisions are agreed upon. |Zowie Zijdemans| | **Spokesperson** communicates group’s questions and problems to the teacher and talks to other teams; presents the group’s findings. |Dilawar Faiz| | **Reflector** observes and assesses the interactions and performance among team members. Provides positive feedback and intervenes with suggestions to improve groups’ processes. |Zowie Zijdemans| | **Recorder** guides consensus building in the group by recording answers to questions. Collects important information and data. |Dilawar Faiz| ## Activities Make sure to have the activities signed off regularly to ensure progress is tracked. Set up a project in CLion to write the small programs needed in some of the activities. ### Activity 1: Memory usage - the sizeof operator Fill out the table below • Run the program you’ve used to obtain the data type sizes in the online compiler explorer. Do you see any differences in the sizes reported? Yes the sizes differ from 1 to 16. • Does the size of a pointer depend on its type? Why (not)? No it doesn't depend on the type. It depends on how many bits your compiler is. Record your answer here ```C #include <stdio.h> int main() { printf("char=%lu\n", sizeof(char)); printf("short int=%lu\n", sizeof(short int)); printf("int=%lu\n", sizeof(int)); printf("long int=%lu\n", sizeof(long int)); printf("floatt=%lu\n", sizeof(float)); printf("double=%lu\n", sizeof(double)); printf("long double=%lu\n", sizeof(long double)); printf("char*=%lu\n", sizeof(char*)); printf("int*=%lu\n", sizeof(int*)); printf("float*=%lu\n", sizeof(float*)); printf("double*=%lu\n", sizeof(double*)); printf("void*=%lu\n", sizeof(void*)); return 0; } ``` ### Activity 2: Array and structure sizes This is how you include code listings in your markdown document: ```C typedef struct { char name[80]; int age; } person_t; void size_array(int array[]) { printf("Size of array parameter: %lu\n", sizeof(array)); } void size_struct(person_t p) { printf("Size of p parameter: %lu\n", sizeof(p)); } int main() { int array[10]; person_t bob = {.name = "Bob", .age = 22}; printf("Size of int array: %lu\n", sizeof(array)); printf("Size of person_t structure: %lu\n", sizeof(bob)); size_array(array); size_struct(bob); } ``` The character size van een structure veranderd niet, het blijft 84 bits (80 bits voor de character array en 4 bits voor de interger age). Maar de int array is wel verschillend. want de een word doorgeven via een functie. ### Activity 3: Memory addresses ```C #include <stdio.h> int main( void ) { int a = 0xA0B0C0D0; short int b = 0x7856; const char * s = "Hello!"; char buf[] = "Pointer"; short int c = 0x3412; printf("int a: %p\n", (void*) &a); printf("short int b: %p\n", (void*) &b); printf("const char *s: %p\n", (void*) &s); printf("char buf[]: %p\n", (void*) buf); printf("short int c: %p\n", (void*) &c); printf("string s first char: %p\n", (void*) &s[0]); } ``` Record your answer here •Add a printf statement to print the memory address of the first character of the "string" s. Are the characters of the string "Hello" stored near the variables a, b, s, and c? No they are not stored near the other variables • Are the variables layed out in a contiguous way in memory, or are there gaps between them? There are gaps between them ### Activity 4: Observing automatic lifetime ```cpp #include <stdio.h> int add(int a, int b) { int c = a + b; printf("Memory adress a: %p\n Memory adress b:%p\n Memory adress c: %p\n\n", a, b, c); return c; } int mul(int x, int y) { int z = x * y; printf("Memory adress x: %p\n Memory adress y:%p\n Memory adress z: %p\n\n", x, y, z); return z; } int main( void ) { printf("%d\n", mul(add(3, 4), add(1, 5))); } ``` output: Memory adress a: 0000000000000001 Memory adress b: 0000000000000005 Memory adress c: 0000000000000006 Memory adress a: 0000000000000003 Memory adress b: 0000000000000004 Memory adress c: 0000000000000007 Memory adress x: 0000000000000007 Memory adress y: 0000000000000006 Memory adress z: 000000000000002A 42 ### Activity 5: Observing the stack int a uses the same address as int x and y ```c= #include <stdio.h> int poly(int a) { printf("a=%p\n", a); int b = a * (a + 1); printf("b=%p\n", b); return b / 2; } int add_polys(int x, int y) { printf("x=%p\n", x); printf("y=%p\n", y); int bx = poly(x); int by = poly(y); printf("bx=%p\n", bx); printf("by=%p\n", by); return bx + by; } int main( void ) { printf("%d\n", add_polys(42, 24)); } ``` Record your answer here ### Activity 6: Leaking local addresses De eerste waarde is 42 omdat er in de functie ptr_amswer gelijk word gezet aan de adress van "answer = 42", De tweede geeft 24 omdat er een array is in de functie. En een array en pointer werkt hetzelfde met memories dus ptr_answer krijgt de waarde van de eerste integer value van de array. ### Activity 7: Memory addresses of local variables • Which warnings and / or errors does the compiler give when compiling this program? note: declared here 6 | int array[10]; undefined reference to `do_some_work(int*, int) • What do these warnings and / or errors mean? ? • Does this approach to create an array at runtime work? Why (not)? No it doesn't work ### Activity 8: Using malloc ```cpp #include <stdio.h> #include <stdlib.h> int* allocate_memory (int count){ return malloc(count * sizeof(int)); } int main( void ) { unsigned long *a; a = (unsigned long*) malloc(sizeof (unsigned long [1])); float *b; b = (float*) malloc(sizeof (float [256] )); printf("%p\n", allocate_memory(a)); printf("%p\n", allocate_memory(b)); ``` ### Activity 9: Using allocated memory as an array • How many int elements can be stored in the allocated block of memory? 20 int element can be stored in the allocated block of memory • What happens when you perform an out-of-bounds access to an array that is stored in the value will be 0 dynamically allocated memory? • What is the problem in the program listed below, and how can it be fixed? Record your answer here ### Activity 10: Infinite memory? the programma chrasht omdat er niet genoeg memory meer over is daarom is er ook een 0 aan het einde van de code. En er waren 209 x 8 bits geprints ### Activity 11: Fixing a memory leak ```cpp #include <stdio.h> #include <stdlib.h> const int SIZE = 512; int main( void ) { char *str = (char*) malloc(sizeof(char[SIZE])); printf("before: %lu \n", str); while (str == NULL) { str = malloc(SIZE); } if (str != NULL) { free(str); } printf("after free :%lu",str); return 0; } ``` uitkomst: before: 12326064 after free : 12326064 de memory is geleegd want na het printen is dezelfde data over omdat je met free de gebruikte datat hebt geleegd ### Activity 12: Dangerous `free`s Als je de free functie gebruikt zonder een malloc dan krijg je een sigtrap error op je compiler. Dat komt omdat je free niet kan gebruiken zonder malloc. Tenzij het een NULL is want Free functie gebruikt void* en daarom kan een null ook gebruikt worden. ### Activity 13: Using realloc Record your answer here 10 keer moet de free functie gebruik worden. ### Activity 14: Using a dynamically sized buffer Record your answer here c``` #include <stdio.h> int main( void ) { char *ptr = NULL; unsigned long capacity = 20; ptr = realloc(ptr, sizeof(char[capacity])); if (!ptr){ fprintf(stderr, "Memory allocation failed\n"); return 1; } FILE *file = fopen("input.txt", "r"); if (!file) { fprintf(stderr, "Error opening file\n"); return 1; } unsigned long count = 0; int c = fgetc(file); while (c != EOF) { /* re-allocate memory pointed to by ptr if count == capacity * don't forget to check if the pointer returned by realloc is not NULL */ if(count==capacity){ capacity= capacity*1.5; ptr = realloc(ptr, sizeof(char[capacity])); } ptr[count++] = (char) c; c = fgetc(file); } } ## Looking back ### What we've learnt Stack vs Heap In onze eigen woorden: Stack is een deel in de memory dat is bedoeld voor snelle simpele waarde die je op een specifiek moment gebruikt. En heap is bedoelt voor complexere waardes die de programmeur zelf in de hand heeft door middel van malloc realloc en free ### What were the surprises \ ### What problems we've encountered We hadden moeite met het gebruiken van de free functie omdat we eerst niet wisten wanneer we die moesten gebruiken ### What was or still is unclear We weten nog steeds niet zo goed wanneer we de malloc realloc en free functies het best kunnen gebruiken tijdens het programmeren ### How did the group perform? Het samenwerken ging wel prima. We hadden de vragen verdeeld en aan het eind controleerde we oplossing. En als we vragen hadden tussendoor vroeg je dat. > Written with [StackEdit](https://stackedit.io/).

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully