Week 4 - Memory
Welcome to CS50 again. This is Week 4 and I will go through my review of this week's content.
Lecture
malloc()
is just memory allocate, which will use the memory from the heap. And heap will grow downwards. There is also another section called stack, and function calls and the variables used will be stored in the stack. After the calling, the memory will be freed. Due to this reason, when we pass parameters by value, we just pass the copy and it won't affect the original value since after the function call, the memory will be freed. To affect the original value, we need to pass the address of the parameters.Use the idea of point 1, we can understand the why in
scanf()
, we need to pass the address of the variable we want to store the input. That's because if we don't pass the address, we can't change the variable, which means we can't store our input into the variable. For example,
To understand it, we can use pass by reference when we want to change the parameters we passed in the function.
When we pass the variable in the
scanf()
, the variable must be initialized. For data type likeint
, it's suffice to just declare the variable. But for data type like pointers, declaration only is not suffice, initialization is also needed. For example
For data type like int
, it’s okay for you not to initialize since it always has valid space, so we can always rewrite the value in that valid space safely. But for pointers, not initializing is dangerous because what p stores is a garbage value (If you don’t initialize after declaring variables, what they have are all garbage values). This garbage value may represent an invalid address in the memory, so you can not write into that address.
When using
scanf()
to read string, scanf won't stop, even if you have specified the length of the string. This is dangerous. But whatget_string()
incs50.h
does is to usemalloc()
repeatedly to allocate more and more memory space to get the string.In the lecture, I really apprecaite Prof David's explanation about
*
(dereferencing). It can be viewed as "go to", for example
In line 4, *p
can be viewed as going to the value store in p
, which is an address and get the value stored in that address.
Section
A pointer usually stores address. For example,
In this code snippet, p
is the name for the pointer and int *
means the type is a pointer that points to int
.
Some key syntax about pointer:
type * is a pointer that stores the address of a type
*x takes a pointer x and gets the value stored at that address
&x takes x and gets its address
fread()
explanation It takes four arguments, To where (an address), what size (the size of a chunk), how many (how many chunkcs to read at a time), from where (an address). For example,
In this code snippet, the size of the chunk is one byte, and we want to read 4 chunks at a time from the file and read them to the uint8_t
array called buffer.
Shorts
Pointers
In C,
NULL
pointer is the simplest pointer available to us. And theNULL
pointer points to nothing.When you create a pointer and you don't set its value immediately, you should always set the value of the pointer to NULL.
When you dereference a pointer that is NULL, you will get a segmentation fault.
To define three pointers using one line, you should write
The size of a pointer is either or byte, depending on the system you are using. For example, in a -bit system, the size of a pointer is byte, and in a -bit system, the size of a pointer is byte.
Defining Custom Data Types
In C, we use
typedef
to create a shorthand or rewritten name for data types. It's structure is below, which is very very important.
Dynamic Memory Allocation
Statically and Dynamically
In this code, x
is stored on the stack. The pointer variable px
is also stored on the stack but the memeory it points to is a block of memory on the heap. To further understand this, see this example,
Dynamically-allocated memory is not automatically returned to the system after finishing using it, so we need to use
free()
to free the dynamically-allocated memory. Otherwise, there will be a memory-leak. However, statically-allocated memory doesn't have this issue since it's stored on the stack and the memory will be freed after the function call.
Call Stack
Stack frame When you call a function, the system sets aside space in memory for that function to do its necessary work.
We frequently call such chunk of memory stack frames or function frames (Not stack only).
More than one function's stack frame may exist in memory at a given time.
For example, if
main()
callsmove()
, which then callsdirection()
, all three functions have open frames.These frames are arranged in a stack. The frame for the most-recently called function is always on the top of the stack.
When a new function is called, a new frame is pushed onto the top of the stack and becomes the active frame.
When a function finishes, its frame is popped off the stack, and the frame below it becomes the active frame again.
File Pointers
fopen()
Notice that write means writing from the beginning, which will erase all the existing data in that file. While append means appending at the end of the file, which won't destroy anything in that file.
2. fclose()
fgetc()
Notice that the file pointer must be read mode, otherwise, it will return an error.
Using
fgetc()
to implementcat
command in Linux, which will print the content of the file.
4. fputc()
Notice that the file pointer must be write or append mode, otherwise, it will return an error.
Using
fputc()
to implementcp
command in Linux, which will copy the content of one file to another file.
5. fread()
Reads quantity number of size bytes from the file and stores them in the buffer.
Notice that the file pointer must be read mode, otherwise, it will return an error.
6. fwrite()
Writes quantity number of size bytes from the buffer to the file.
Notice that the file pointer must be write or append mode, otherwise, it will return an error.
Problem Set 4
Things to notice in the problem statement
The wav file has two parts, one is a 44 byte header, the other is the sample part.
Divide and Conquer
Take-aways
In
fopen()
andfwrite()
, the opened file “remembers” the number of bytes that were successfully read, such that subsequent calls to this function for stream will return bytes after those already read.fopen()
andfwrite()
will return the number of items read/written.
Things to notice in the problem statement
The bmp file is made up of pixels and each pixel is composed of 3 Bytes, one for Red, one for Blue and one for Green.
Divide and Conquer
grayscale()
sepia()
reflect()
blur()
Useful Snippets
reflect()
Notice that we only need to iterate over the left side of the pixels. And we cannot let j to be <= width / 2
since one pixel will be swapped twice as the index starts from 0. Also, the index of the corresponding right pixel is needs another minus 1 from width - j
.
2. blur()
Notice that the most consice way to calculate the blur is to use a nested loop as shown in the code snippet above. Also, since we will update our image, we need to create a copy of the original image to calculate the blur. Otherwise, we may run into the resource conflict.
Things to notice in the problem statement
The first three functions (
grayscale()
,reflect()
andblur()
) are the same as the previous question. So, in this part, I will only talk about theedge()
.
Divide and Conquer
edge()
Useful Snippet
edge()
Notice that to use initializer to initialize a multi-dimension array, we need to use {}
to enclose each row.
Things to notice in the problem statement
Each JPEG starts with a distinct header
First three bytes:
0xff
,0xd8
,0xff
Last Byte:
0xe0
to0xef
JPEGs stored back-to-back in memory card
Divide and Conquer
Take-aways
To make sure a byte start with
e
in this question, we can use the idea of bitwise operation to achieve this. In this problem,(buffer[3] & 0xf0) == 0xe0
can serve this purpose very well.The File pointer (
FILE *
) is also allocated on the heap, so at the end of the program, remember to close the files you have opened. In this problem, don't forget to close thecard.raw
.
Last updated