A pointer that points to a freed block of memory is called a stale pointer. Stal
ID: 3730432 • Letter: A
Question
A pointer that points to a freed block of memory is called a stale pointer. Stale pointers are insidious in that dereferecing them does not always fail, even though it should. If the pointer was just magically set to NULL upon being freed, then you'd get a seg fault. Your friend writes this wrapper around free to do just this for ints:
void freeint(int *p) {
free(p);
p = null;
}
Try this code out with our own main and see if it crashes on dereferencing a stale pointer. Spoiler, it doesn't. Describe whats wrong and rewrite the code to work as intended. After writing freeint, write a more general stalefree that works for all types but still complies without warnings
Explanation / Answer
#include "stdafx.h"
#include <iostream>
void freeint(int** p)
{
if(*p)
{
free(*p);
*p = NULL;
}
}
int main()
{
int *x = new int;
freeint(&x);
freeint(&x);
return 0;
}
// Above code works fine because we are actually checking the memory is freed before or not.First we allocate the memory and then freed and again we are trying to free the memory but the pointer which is pointing to memory is NULL so it wont crash for this code.
// Generic approach would be by using "void"
// MemoryLeakTestPro.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
void freeint(void** p)
{
if(*p)
{
free(*p);
*p = NULL;
}
}
int main()
{
void *x = new int;
freeint(&x);
freeint(&x);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.