# Week 4

## Memory

• take memory as a rectangle:

• “text”: machine code
• “data”: variables
• “stack”: used for functions. Like the main function in C. When then next function called, will have its own chunk of memory. Each block is individually addressed.

## String

• C doesn’t have string type data, it’s the first char’s address of the string in memory, ends with \0.

• So, string s = get_string(); equals with char *t = get_string();. s and t are just the address of first character in memory.

• compare two string ?

• copy strings, don’t forget to free the memory

## Pointers

• a swap function to sway ints:

## Memory Leaks

• valgrind is another command-line tool for checking memory leaks.

• valgrind --leak-check=full ./memory // ./memory is our commnd
• “Stack Overflow” is the term for stack that has grown too large, perhaps if we have a recursive function that calls itself too many times.

• “Heap Overflow” is the term for a heap that is too large, perhaps if we called malloc for large chunks of memory without ever calling free.

• “Buffer Overflow” is the overarching term for when too much data is placed into a finite amount of allocated space.

• For example:

• With a short string less than 12, it will be still ok. But if large than 12, it will overwritten with the address of the beginning of the string, even rewrite the main function:

## Images

• Each grid is a pixel, since an image has a finite size and thus finite information in it.

• JPEG

• JPEG files all start with the same three bytes, 255, 216, 255 as a standard, to indicate its filetype.
• 255 in decimal is 1111 1111, and 216 is 1101 1000. Each of those four bits, since they can hold 16 values, map perfectly to hexadecimal. 1111 is f, 1101 is d, and 1000 is 8. So 255 is the same as ff, and 216 is the same as d8. And it’s convention to write hexadecimal as 0xff and 0xd8.
• BMP

• Files are just a sequence of bits, and if we think of each byte as having some offset from the beginning, we can specify exactly what should be in a file for it to be valid.

## Struct

• sample code:

• FILE, write into files