Lecture File
cmd_line.pdf
Shell & CLI
Command-line argument parsing and dynamic 2D array memory management in C.
File/lecture name: cmd_line.pdf
Main theme: Command Line Argument Parsing and Multi-dimensional Array Memory Management in C.
Prereqs assumed by slides: Basic C syntax, understanding of main, printf, malloc, and pointer basics (specifically char * and int *).
What this lecture enables you to do:
main via argc and argv.char *argv[] and char **argv.main are treated as pointers.int **) vs. contiguous memory.| Name | Definition | Why it matters | Common confusion / misconception | Tiny example |
|---|---|---|---|---|
| Command Line Arguments | Data passed to a program via the shell (bash) before execution. | Allows programs to be configurable without recompilation. | Thinking arguments are global variables; they are passed to main. |
./prog arg1 arg2 |
| argc | An integer representing the count of arguments passed (including program name). | Determines the loop bounds for iterating over arguments. | Forgetting that argc includes the program name itself. |
argc = 3 for ./prog a b |
| argv | A pointer to an array of pointers to null-terminated strings (char *argv[]). |
Holds the actual string values of the arguments. | Thinking argv is a 2D array of chars; it is an array of pointers. |
argv[0] is the program name. |
| Spiral Rule | A mnemonic to read C types clockwise from the variable name. | Helps deduce complex pointer types like char **. |
Applying it counter-clockwise or ignoring the brackets. | argv[]*char -> array of pointers to chars. |
| Array Decay | The phenomenon where an array parameter is treated as a pointer to its first element. | Explains why main takes char *argv[] but it acts like char **argv. |
Believing argv is strictly an array and not a pointer. |
char *argv[] is equivalent to char **argv. |
| Double Indirection | Accessing data through two levels of pointers (e.g., matrix[i][j]). |
Necessary for standard 2D array implementation using malloc. |
Assuming it is faster than 1D arrays; it is actually slower. | matrix[i] gets a row pointer, matrix[i][j] gets the int. |
| Memory Leak | Allocating memory but failing to free it before the program exits. | Wastes heap space and can cause crashes in long-running programs. | Freeing the outer pointer (matrix) without freeing inner rows. |
free(matrix) loses access to inner malloc blocks. |
| 1D Simulation | Using a single contiguous block of memory to represent a 2D grid. | Improves cache locality and reduces memory overhead (no pointer array). | Forgetting to multiply the row index by the column count. | arr[i*m + j] accesses row i, col j. |
1. How to access command line arguments safely
argc to ensure enough arguments exist before accessing argv.i = 0 to i < argc.argv[i] as a char * (string).argv[0] is the program name, not the first user argument.2. How to allocate a 2D array (int **) correctly
int **matrix = malloc(n * sizeof(int*));i from 0 to n-1.int *row = malloc(m * sizeof(int));row[j] = ...).matrix[i] = row;matrix.3. How to free a 2D array without leaking memory
i from 0 to n-1).free(matrix[i]);free(matrix);matrix before freeing matrix[i], or you lose the pointers to the inner blocks.4. How to simulate a 2D array with a 1D array
int *matrix = malloc(n * m * sizeof(int));(i, j) using the formula: matrix[i * m + j].m (columns) must be known to calculate the offset.| Pattern name | When to use it | Correct minimal example | Common bug + how to avoid it |
|---|---|---|---|
| Arg Parsing Loop | When processing CLI flags or values. | for (size_t i = 0; i < argc; ++i) { printf("%s\n", argv[i]); } |
Bug: Accessing argv[argc] (undefined behavior). Fix: Loop strictly < argc. |
| 2D Allocation | When creating a matrix of dynamic size. | int **m = malloc(n * sizeof(int*));for(i) m[i] = malloc(m_cols * sizeof(int)); |
Bug: Forgetting to store row pointer in matrix[i]. Fix: Explicitly assign matrix[i] = row;. |
| 2D Deallocation | When cleaning up a dynamically allocated matrix. | for (size_t i = 0; i < n; ++i) free(matrix[i]);free(matrix); |
Bug: Calling free(matrix) first. Fix: Always free inner rows first. |
| 1D Indexing | When optimizing for cache or simplicity. | data[i * width + j] |
Bug: Using i * height + j (wrong dimension). Fix: Multiply by the number of columns (width). |
argv[argc].i < argc is violated or argv is accessed out of bounds.i < argc.argv[0] is empty or unexpected.argv[0] is the executable name.argv[0] to be the program name (e.g., ./prog).printf prints garbage characters for argv[i].argv[i] is not null-terminated or points to invalid memory.argv is guaranteed to be null-terminated by convention.int *matrix) for large datasets.char *argv[] in main.char **argv if preferred.malloc returns NULL but code proceeds.if (ptr == NULL) after malloc.free(matrix) causes double free error.matrix after freeing matrix[i] inside the loop.matrix is only freed once, after all inner rows are freed.argv type deduction is confusing.argv[]*char clockwise: array of pointers to chars.i * n + j instead of i * m + j.m is the column count (width).sizeof(int*) vs sizeof(int) mismatch.sizeof(int) instead of sizeof(int*).sizeof(int*).main.argc count.argc includes the program name as the first argument.argv is treated as a 2D array of chars.char *argv[] with char argv[][N].argv is an array of pointers to strings, not a block of chars.free order is reversed.free(matrix) before the loop.argv in int main(int argc, char *argv[])?
A: It is an array of pointers to characters (char *argv[]), which decays to a pointer to a pointer (char **argv).argv[0] always the program name?
A: By convention, the operating system passes the executable name as the first argument before the user-provided arguments.free(matrix) immediately after allocating a 2D array?
A: You lose access to the pointers to the inner arrays, causing a memory leak because the inner malloc blocks cannot be freed.(i, j) in a 1D array simulating an n x m matrix?
A: index = i * m + j.argc is 3, what are the valid indices for argv?
A: Indices 0, 1, and 2. argv[3] is undefined behavior.malloc?
A: First, iterate and free each inner row (matrix[i]), then free the outer array (matrix).char **argv mean?
A: A pointer to a pointer to a character.argv be declared as char argv[][N]?
A: No, argv is an array of pointers to strings, not a fixed-size 2D char array.int **matrix = malloc(n * sizeof(int*))?
A: n (the number of rows).malloc failing?
A: It returns NULL. Accessing the pointer without checking leads to a crash.argc: Count of arguments (includes program name).argv: Array of pointers to strings (char *argv[]).argv[0]: Program name.argv[1]: First user argument.sizeof(int*): Size of a pointer (use for outer array allocation).sizeof(int): Size of an integer (use for inner row allocation).malloc(n * sizeof(int*)) then loop malloc(m * sizeof(int)).free(matrix[i]) then free(matrix).arr[i * cols + j].char *argv[] is effectively char **argv.main.argv is an array of pointers.\0 character.std::vector, std::string) are not covered; this is C.n and m) passed to malloc; it does not cover resizing arrays.getopt for handling flags (e.g., -l, -w).malloc.malloc); stack arrays are mentioned only as a contrast.argc & argv Definition (Slide 3 / "argc & argv")argv Type (char **) (Slide 6 / "argvreally")Manually curated from summaries/cmd_line.txt. Use this page as a study aid and cross-check official slides for grading-critical details.