My Cs50 Week 4 Lecture’s summary: Memory

Welcome to halfway of Cs50, previous week’s lecture and psets have been interesting, thanks to Prof. David J. Malan.

This week was all about Memory which includes Hexadecimal, Pointers, Dynamic Allocated memory, File Pointer, Call Stack, defining custom types, and others.

Cs50 Week 4 Summary

Oh yeah, as I said earlier, we talked about pointers, hexadecimal, using malloc, call stack, and others. let me explain…

Hexadecimal is a way of representing data on a computer system.

  • Hexadecimal make mapping easy, a group of 4 binary digits represents a single hexadecimal digit, 0000 means 0, 0001 means 1, 0010 means 2, 0011 means 3, 1010 means A in hexadecimal, and so on.
  • To convert from hexadecimal to binary, we need to take 4 binary, 0 & 1 from right to left together, and use it to represent one hexadecimal digit.
binary to hexadecimal mapping

Pointers: They are address to locations in memory where variable lives. which we can think of as a value that points to a location in memory.

  • The (*) operator let us go to the location that a pointer is pointing to. they provide an alternative way to pass data between functions.
  • When we pass data by pointers, we have the power to pass the actual value itself, that means a change that is made in one function can impact what happen at different function.
  • If x is an int type variable, then &x is a pointer to int whose value is the address of x.
  • the main purpose of a pointer is to allow us to modify or inspect the location to which it points, we do this by dereferencing the pointer

Dynamic Memory allocation: memory allocation is an int built function in c. This function is used to assign a specified amount of memory for an array to be created. It also returns a pointer to the space allocated in memory using this function.

  • The dynamic allocated memory comes from a pool of memory known as Heap while memory that is being given a variable name come from the Stack
  • We get dynamically allocated memory by making a call to the C standard library function malloc(), passing as its parameter the number of bytes requested, for example… Int *px = malloc(sizeof(int));
  • After allocating a memory, we need to free it with free(px), and only memory allocated be freed.

Example showing malloc explanation

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
    int count;
    printf("How many integer do you want to allocate memory for: ");

    scanf("%d", &count);

    int *memory = malloc(count * sizeof(int));  //allocate a memory at run time

    if (memory == NULL)  //to check if memory is equal to null
    {
        printf("Memory not allocated\n");
    }
    else
    {
        printf("the address of the pointer is %p\n", memory);  //this shows the section of address where memory is allocated

        for (int i = 0; i < count; i++)
        {
            memory[i] = i;   //we iterate and assign value to where memory is allocated
        }

        for (int i = 0; i < count; i++)
        {
            printf("%i\n", memory[i]);  //printing the value store in the memory
        }
    }
    free(memory);   //to free memory being allocated back
}

We also have Valgrind, which is a command tool, we can use to run our program and see if there if have any memory leaks.

Call Stack: This is what program use to store information about the active subroutines in a computer program, it is what a program uses to keep track of method calls. The call stack is made up of stack frames

  • When we call a function, the system sets aside space in memory for that function to do its necessary work, we frequently call such chunks of memory stack frames or function frames
  • More than one function’s stack frame may exist in memory at a given time. If main() calles move(), which then calls direction(), all three functions have open frames.

FILE POINTER: A file pointer is a pointer that is used to handle and keep track on the files being accessed. A new data type called “FILE” is used to declare file pointer. This data type is defined in stdio.h file.

  • File pointer is declared as FILE *fp, where, ‘fp’ is a file pointer
  • Example are fopen(), fclose(), fgetc(), fputc(), fread() fwrite(), which are some of the most common I/O fucntions.

Fopen(), which is used to open a file and it returns a file pointer to it.

  • It’s been define like this FILE* ptr = fopen(<filename>, <operation>);

fclose(), which closes the file pointed to by the given file pointer.

  • usage like this fclose(<file pointer>);

fgetc(), it reads and returns the next character from the file pointed to. The operation of the file pointer passed as in as a parameter must be “r” for reading or you will suffer an error.

  • char ch = fgetc(<file pointer>);

an example below showing how fgetc is being used

#include <stdio.h>

int main(void)
{
    FILE *ptr = fopen("file.txt", "r"); //to open a file for reading or writing which accept this mode "w"
    if (ptr == NULL)
    {
        printf("Error while opening files");
        return 0;
    }
    char ch;
    while ((ch = fgetc(ptr)) != EOF)   //to print out all character in the file
    {
        printf("%c", ch);
    }
    fclose(ptr);
}

fputc(), it writes or appends the specified character to the pointer to file, the operation of the file pointer passed in as parameter to must be open for “w” or “a”, writing or appending, or you will suffer an error.

  • fputc(<character>, <file poimter>);

fread(), which reads <qty> units of <size> from the file pointed to and stores them in a memory in a buffer (usually an array) pointed to by <buffer>.

  • The operation of the file pointer passed in as a parameter must be “r” for read, or you will suffer an error.
  • fread(<buffer>, <size>, <qty>, <file pointer>);

an example below showing how fread() is being used

#include <stdio.h>

int main(void)
{
    FILE* file = fopen("file.txt", "r");  //open file for reading
    if(file == NULL)
    {
        printf("Error while opening file");
        return 1;
    }
    char buffer[100];  //location where to store input from file.txt
    fread(buffer, sizeof(char), 90, file); // all parameters needed stored

    printf("Data read from file: %s\n ", buffer); //print input collected from file.txt to the terminal
    fclose(file); //then closing file
}

fwrite(), writes <qty> units of size <size> to the file pointed to by reading them from a buffer (usually an array) pointed to by <buffer>

  • fwrite(<buffer>, <size>, <qty>, <file pointer>);

Note: the operation of the file pointer passed in as a parameter must be “w” for write or “a” for append, or you will suffer an error.

example below

#include <stdio.h>

int main(void)
{
    FILE* file = fopen("file.txt", "w");  //open file for writing
    if(file == NULL)
    {
        printf("Error while opening file");
        return 1;
    }
    char buffer[100] = "I want to become a Cybersecurity Analyst"; //write this text to file.txt
    fwrite(buffer, sizeof(char), 90, file); // all parameters needed stored

    printf("Data read from file: %s\n ", buffer); //print input collected from file.txt

    fclose(file); //then closing file
}

Conclusion

It has been a tough week with definitely new syntax of code, I hope the problem set from this week’s lecture will be interesting and less intimidating.

Thanks for reading

Note: This content is the overview of what I learned from the online cs50x week 4 lecture, thanks to David.J Malan, Doug Lloyd, and others

Leave a Reply