Still learning more about C

Useful Functions



printf("there's %d apples", apple_count);

Print a line to the output, takes standard string formatting

count = atoi(argv[2]);

Convert a string to an int, ASCII to Integer (atoi)

Memory Segments

Text Segment

Also called code segment, all assembly for code is stored in this location. There is no write permission for this location, it does not store variables, and has a fixed length. Nothing should ever change in it, program will be killed if anything is changed in this section of memory.

Data and BSS Segments

Data contains the initialized global and static variables, while BSS has the uninitialized counterparts. These segments are writable but are a fixed size.

Heap Segment

Memory location programmer can directly control. Can be allocated and used for any purpose, no fixed size and can grow or shrink as needed. Growth of the heap goes downward to higher memory addresses.

Stack Segment

The stack is used to store local function variables and context during function calls. All of this information is stored on a stack frame to keep it in memory. First in Last out (FILO), imagine putting pancakes on a plate, you'll need to remove the pancakes in order to reach lower ones. Adding items to the stack is pushing, while removing items is popping. The ESP (Extensible Stack Pointer) is used to keep track of the addess of the end of the stack. The stack grows upward, towards lower memory addresses.

The EBP (Extensible Base Pointer) contains the base address of the function's frame and is used to reference local function variables in the current stack frame. The SFP (Saved Frame Pointer) is used to restore EBP to its previous value and the Return Address is used to restore EIP to the next instruction found after the function call (where to return in the program after completing the current function).

Remember, the stack is FILO, so function calls place the parameters on the stack in reverse order. Take the code example below into account.

int main() {
    test_function(1, 2, 3, 4);  // Order of parameters is reversed when placed on stack

Code Examples

Examples of code used to identify and use for functionality

Read Command Line Args

Simple program to read the amount of command line args given and prints each one to a newline

#include <stdio.h>

int main(int arg_count, char *arg_list[]) {
        int i;
        printf("There were %d args given:\n", arg_count);
        for(i=0; i < arg_count; i++)
                printf("arg %d: %s\n", i, arg_list[i]);

Last updated