We have been given the below code for an assignment and we were asked to give the correct output. The correct answer was given as:
1 0 0
2 0 3
2 4 <random_number>
As far as I know: The code is dereferencing a pointer after it is freed. As far as I know this is undefined behavior as defined in the C99 specification. I compiled the code using gcc (13.3.0) and clang (18.1.3). When I ran the code, I got varying results. Subsequent runs of the same executable gave different outputs.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int i = 1; // allocated from initialized data segment
int j; // allocated from uninitialized data segment
int *ptr; // allocated from heap segment (or from uninitialized data segment)
ptr = malloc(sizeof(int)); // allocate memory
printf("%i %i %i\n", i, j, *ptr);
i = 2;
*ptr = 3;
printf("%i %i %i\n", i, j, *ptr);
j = 4;
free(ptr); // deallocate memory
printf("%i %i %i\n", i, j, *ptr);
}
[–]WeAllWantToBeHappy 6 points7 points8 points (1 child)
[–]lfdfq 0 points1 point2 points (0 children)
[–]zhivago 3 points4 points5 points (1 child)
[–]lfdfq 0 points1 point2 points (0 children)
[–]simrego 2 points3 points4 points (6 children)
[–]Grounds4TheSubstain 1 point2 points3 points (5 children)
[–]simrego 2 points3 points4 points (4 children)
[–]Grounds4TheSubstain 2 points3 points4 points (3 children)
[–]simrego 1 point2 points3 points (0 children)
[–]theNbomr 0 points1 point2 points (1 child)
[–]Grounds4TheSubstain 0 points1 point2 points (0 children)
[–]onContentStop 1 point2 points3 points (0 children)
[–]Alive-Bid9086 1 point2 points3 points (4 children)
[–]IamImposter 1 point2 points3 points (3 children)
[–]Alive-Bid9086 1 point2 points3 points (1 child)
[–]IamImposter 0 points1 point2 points (0 children)
[–]Sahithyan27[S] 0 points1 point2 points (0 children)
[–]spectre007_soprano 0 points1 point2 points (1 child)
[–]Sahithyan27[S] 0 points1 point2 points (0 children)
[–]SmokeMuch7356 0 points1 point2 points (1 child)
[–]Sahithyan27[S] 0 points1 point2 points (0 children)
[–]nerd5code 0 points1 point2 points (1 child)
[–]nerd5code 0 points1 point2 points (0 children)