Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

LANGUAGE: C Below we are dissecting the structure of atoi and its pitfalls using invalid calls Below are invalid calls to atoi Please answer the

LANGUAGE: C

Below we are dissecting the structure of atoi and its pitfalls using invalid calls

image text in transcribed

Below are invalid calls to atoi

image text in transcribed

Please answer the following questions just in the context/frame provided based on your understanding of how this function works. Yes there are warnings when you run this code, but I am just trying to understand the return values.

a)

&num returns 2, I am aware that 'num' -'0' has a value of 2 but not why isdigit fails to recognize that & is not a digit, and moreover why it fails to recognize that n, u, or m isn't a digit. Is it because isdigit accepts an int as a parameter so we are casting that value? Then again, why didn't isdigit stop at &? isdigit then seems like a fairly counterintuitive function to use, but I still need light shed on this call.

b)

On a somewhat similar note, num causese the program to crash "Program terminated with signal SIGSEGV, Segmentation fault." Is this because we are attempting to access the memory address at the value "num" (or are we attempting to access the memory address at 50?) since we are dealing with a pointer in atoi? If not, please tell me why this program crashes when passed num.

C)

-2147483649 is the equivalent of INT_MIN -1, and so when passed in it overflows and returns INT_MAX because we are storing n into type int as we convert it, this makes sense. Why, then, is there a comment in the code saying we calculate it as a negative value to prevent INT_MIN overflow, even though INT_MIN overflow appears to be exactly what happened? Please explain why we calculated it as a negative AND why it overflowed if we have this supposed safety mechanism in place? What then is the safety mechanism for?

int atoi(const char *s) int n-e, neg-0; while (isspace(*s)) s++; switch (*s) ( case -': neg-1; case s++; * Compute n as a negative number to avoid overflow on INT_MIN while (isdigit(*s)) n 10*n (*s++ '0' ); - - return neg ? n : -nj

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Infrastructure For Medical Research In Databases

Authors: Thomas Heinis ,Anastasia Ailamaki

1st Edition

1680833480, 978-1680833485

More Books

Students also viewed these Databases questions

Question

What are the adaptive strategies?

Answered: 1 week ago