Entrance Exams
Govt. Exams
int *p = NULL;
int *q = malloc(sizeof(int));
free(q);
free(q);
What is the issue here?
Freeing the same pointer twice causes double free error and undefined behavior. Should set q=NULL after first free.
char *str = "Hello";
str[0] = 'J';
String literals are stored in read-only memory. Attempting to modify causes undefined behavior or segmentation fault.
int (*ptr)(int, int) declares a pointer to a function. int *ptr(int, int) declares a function returning pointer to int.
Valid pointer arithmetic includes addition/subtraction with integers and subtraction between pointers. Multiplication, division, and pointer addition are invalid.
void func(int *arr) { arr[0] = 100; }
int main() {
int a[5] = {1,2,3,4,5};
func(a);
printf("%d", a[0]);
}
Arrays are passed by reference (as pointers). Changes made in func() affect the original array. a[0] becomes 100.
char *str = "Hello";
printf("%c", *(str+1));
str points to 'H', str+1 points to 'e'. Dereferencing gives 'e'.
Calling free() on already freed memory or using a pointer after freeing it causes double-free errors and use-after-free bugs, leading to undefined behavior.
int x = 100, y = 200;
int *p = &x;
int *q = &y;
p = q;
printf("%d", *p);
p is reassigned to point to y (p = q). Dereferencing p now gives the value of y, which is 200.
int **p declares a pointer to a pointer (double pointer). Each * adds one level of indirection.
int *p, *q;
int x = 5;
p = &x;
q = p;
printf("%d %d", *p, *q);
Both p and q point to the same variable x. Dereferencing both gives the value 5.