Pointers and Memory Management Flashcards
(33 cards)
What is a memory address?
A unique identifier for a location in memory where data is stored.
How is memory allocated when declaring a variable?
The system reserves memory space and updates the lookup table with its address.
What happens when you assign a value to a variable?
The system finds the variable in the lookup table, goes to the memory address, and stores the value.
What is a pointer?
A variable that stores the memory address of another variable.
How do you declare a pointer?
<datatype> *pointer_name;
## Footnote
Example: int *p; declares a pointer to an integer.
</datatype>
What does the & operator do?
It returns the memory address of a variable.
What does the * operator do when used with a pointer?
It dereferences the pointer to access the value stored at the memory address.
How do you assign a pointer to a variable’s address?
p = &variable;
What happens when you change the value at a pointer’s address?
The value stored in the original variable changes.
How do you print a pointer’s address in C?
Using %p in printf: printf(“Address: %p\n”, p);
What happens when you increment a pointer?
The pointer moves to the next memory location based on its data type size.
If x is a pointer to an int, what does x++ do?
It moves x to the next integer’s address (typically increasing by 4 bytes).
How are arrays and pointers related?
The array name is a pointer to the first element.
What is equivalent to array[i] using pointers?
*(array + i)
What happens when you assign an array to a pointer?
The pointer stores the address of the first element.
What is the output of this code?
char str[] = “Hello”;
char *p = str;
printf(“%s\n”, p);
“Hello”
What is a void pointer?
A pointer that can hold the address of any data type.
Why do you need to cast a void pointer before dereferencing?
Because its data type is unknown, so you must specify it.
How do you cast a void pointer to a char *?
(char *)p
Why is dynamic memory allocation needed?
To allocate memory at runtime when the size is unknown at compile time.
What function is used to allocate dynamic memory?
malloc()
What does malloc() return?
A pointer to the allocated memory (or NULL if allocation fails).
What happens if you forget to free memory allocated with malloc()?
A memory leak occurs.
How do you free dynamically allocated memory?
free(pointer);