How should I verify that an integer value passed in from argv won't overflow? The Next CEO of...
Gauss' Posthumous Publications?
Why can't we say "I have been having a dog"?
Can you teleport closer to a creature you are Frightened of?
How does a dynamic QR code work?
Is it possible to make a 9x9 table fit within the default margins?
Could you use a laser beam as a modulated carrier wave for radio signal?
Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?
Free fall ellipse or parabola?
How exploitable/balanced is this homebrew spell: Spell Permanency?
Planeswalker Ability and Death Timing
Compensation for working overtime on Saturdays
Strange use of "whether ... than ..." in official text
Ising model simulation
Is it okay to majorly distort historical facts while writing a fiction story?
Is it a bad idea to plug the other end of ESD strap to wall ground?
The sum of any ten consecutive numbers from a fibonacci sequence is divisible by 11
Is there a rule of thumb for determining the amount one should accept for a settlement offer?
Another proof that dividing by 0 does not exist -- is it right?
How can a day be of 24 hours?
MT "will strike" & LXX "will watch carefully" (Gen 3:15)?
That's an odd coin - I wonder why
Calculating discount not working
Horror film about a man brought out of cryogenic suspension without a soul, around 1990
Man transported from Alternate World into ours by a Neutrino Detector
How should I verify that an integer value passed in from argv won't overflow?
The Next CEO of Stack OverflowWhy is there no strtoi in stdlib.h?How to detect unsigned integer multiply overflow?Write a program that sums the sequence of integers, as well as the smallest in the sequenceImprove INSERT-per-second performance of SQLite?Speed comparison with Project Euler: C vs Python vs Erlang vs HaskellC Programming: How to read input byte at a time and output only integers as tokens?How to avoid overflow error when finding LCM for series of large integersDoes the implementation of strtoul in glibc conflicts with the C11 standard?How do I re enter an integer value in a 'while' loop?C - Can't read user integer inputHow I can handle integer overflow?
I have a program that requires the user to enter an integer as a command line argument, in the form of ./program 100
.
Obviously this will read the value in as a string, so I need to parse it to an integer. I have to ensure that the input value won't overflow an integer variable. I have read about strtol()
, but it works with long variables and I have to stick with a regular int.
Is there anything similar that can be used for an int?
c
|
show 10 more comments
I have a program that requires the user to enter an integer as a command line argument, in the form of ./program 100
.
Obviously this will read the value in as a string, so I need to parse it to an integer. I have to ensure that the input value won't overflow an integer variable. I have read about strtol()
, but it works with long variables and I have to stick with a regular int.
Is there anything similar that can be used for an int?
c
7
Usestrtol
and compare to INT_MAX/MIN.
– Eugene Sh.
4 hours ago
2
if (longvalue > INT_MAX) /* overflow */;
don't forget to#include <limits.h>
– pmg
4 hours ago
1
@pmg check would fail for platforms whensizeof(int) == sizeof(long) = true
.
– SergeyA
4 hours ago
1
@pmg, you can do it in a single check by just comparing for>= INT_MAX
. This will always work.
– SergeyA
4 hours ago
1
@SergeyA Yeah, apparently one should handlestrtol
errors too. I assumed OP is already aware of that when mentioned usingstrtol
.
– Eugene Sh.
4 hours ago
|
show 10 more comments
I have a program that requires the user to enter an integer as a command line argument, in the form of ./program 100
.
Obviously this will read the value in as a string, so I need to parse it to an integer. I have to ensure that the input value won't overflow an integer variable. I have read about strtol()
, but it works with long variables and I have to stick with a regular int.
Is there anything similar that can be used for an int?
c
I have a program that requires the user to enter an integer as a command line argument, in the form of ./program 100
.
Obviously this will read the value in as a string, so I need to parse it to an integer. I have to ensure that the input value won't overflow an integer variable. I have read about strtol()
, but it works with long variables and I have to stick with a regular int.
Is there anything similar that can be used for an int?
c
c
asked 4 hours ago
JakeJake
109212
109212
7
Usestrtol
and compare to INT_MAX/MIN.
– Eugene Sh.
4 hours ago
2
if (longvalue > INT_MAX) /* overflow */;
don't forget to#include <limits.h>
– pmg
4 hours ago
1
@pmg check would fail for platforms whensizeof(int) == sizeof(long) = true
.
– SergeyA
4 hours ago
1
@pmg, you can do it in a single check by just comparing for>= INT_MAX
. This will always work.
– SergeyA
4 hours ago
1
@SergeyA Yeah, apparently one should handlestrtol
errors too. I assumed OP is already aware of that when mentioned usingstrtol
.
– Eugene Sh.
4 hours ago
|
show 10 more comments
7
Usestrtol
and compare to INT_MAX/MIN.
– Eugene Sh.
4 hours ago
2
if (longvalue > INT_MAX) /* overflow */;
don't forget to#include <limits.h>
– pmg
4 hours ago
1
@pmg check would fail for platforms whensizeof(int) == sizeof(long) = true
.
– SergeyA
4 hours ago
1
@pmg, you can do it in a single check by just comparing for>= INT_MAX
. This will always work.
– SergeyA
4 hours ago
1
@SergeyA Yeah, apparently one should handlestrtol
errors too. I assumed OP is already aware of that when mentioned usingstrtol
.
– Eugene Sh.
4 hours ago
7
7
Use
strtol
and compare to INT_MAX/MIN.– Eugene Sh.
4 hours ago
Use
strtol
and compare to INT_MAX/MIN.– Eugene Sh.
4 hours ago
2
2
if (longvalue > INT_MAX) /* overflow */;
don't forget to #include <limits.h>
– pmg
4 hours ago
if (longvalue > INT_MAX) /* overflow */;
don't forget to #include <limits.h>
– pmg
4 hours ago
1
1
@pmg check would fail for platforms when
sizeof(int) == sizeof(long) = true
.– SergeyA
4 hours ago
@pmg check would fail for platforms when
sizeof(int) == sizeof(long) = true
.– SergeyA
4 hours ago
1
1
@pmg, you can do it in a single check by just comparing for
>= INT_MAX
. This will always work.– SergeyA
4 hours ago
@pmg, you can do it in a single check by just comparing for
>= INT_MAX
. This will always work.– SergeyA
4 hours ago
1
1
@SergeyA Yeah, apparently one should handle
strtol
errors too. I assumed OP is already aware of that when mentioned using strtol
.– Eugene Sh.
4 hours ago
@SergeyA Yeah, apparently one should handle
strtol
errors too. I assumed OP is already aware of that when mentioned using strtol
.– Eugene Sh.
4 hours ago
|
show 10 more comments
2 Answers
2
active
oldest
votes
You can use strtol
for this. You'll first need to check if this function fails to convert the value. If it convert successfully, then check if the value is in the range of INT_MIN
to INT_MAX
:
errno = 0;
long x = strtol(argv[1], NULL, 10);
if (errno) {
perror("conversion failed");
} else if (x < INT_MIN) {
printf("value too smalln");
} else if (x > INT_MAX) {
printf("value too bign");
} else {
printf("value = %ldn", x);
}
Note that this will work whether long
is the same size as int
or larger.
If sizeof(long) > sizeof(int)
, the INT_MIN
and INT_MAX
checks will catch the cases where the value fits in a long
but not an int
. If sizeof(long) == sizeof(int)
, an out of range value will result in errno
being set to non-zero to catch the error, and the INT_MIN
and INT_MAX
cases will never be true.
2
Strictly speaking, it's the ranges ofint
andlong
that are relevant here, not their sizes. In the presence of padding bits, it's possible forint
andlong
to have the same size, but forlong
to have a wider range. (Few if any implementations actually use padding bits, though.)
– Keith Thompson
4 hours ago
if (errno) {
is not a sufficient test to detect "conversion failed" aserrno
can still be 0.
– chux
1 hour ago
add a comment |
How should I verify that an integer value passed in from argv won't overflow?
Use strtol()
and check the end pointer. Then check errno
and maybe a range test
if (argc > 1) {
char *endptr;
errno = 0;
long num = strtol(argv[1], &endptr, 10);
if (argv[1] == endptr) {
puts("No conversion");
} else if (errno == ERANGE) {
puts("Value outside long range");
#if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
} else if (num < INT_MAX || num > INT_MAX) {
errno = ERANGE;
puts("Value outside int range");
#endif
} else {
// If code wants to look for trailing junk
if (*endptr) {
puts("Non-numeric text");
} else {
printf("Success %dn", (int) num);
}
}
Based on Why is there no strtoi in stdlib.h?
#else
should be#endif
– chqrlie
2 hours ago
@chqrlie Yes, code amended.
– chux
1 hour ago
add a comment |
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55462918%2fhow-should-i-verify-that-an-integer-value-passed-in-from-argv-wont-overflow%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can use strtol
for this. You'll first need to check if this function fails to convert the value. If it convert successfully, then check if the value is in the range of INT_MIN
to INT_MAX
:
errno = 0;
long x = strtol(argv[1], NULL, 10);
if (errno) {
perror("conversion failed");
} else if (x < INT_MIN) {
printf("value too smalln");
} else if (x > INT_MAX) {
printf("value too bign");
} else {
printf("value = %ldn", x);
}
Note that this will work whether long
is the same size as int
or larger.
If sizeof(long) > sizeof(int)
, the INT_MIN
and INT_MAX
checks will catch the cases where the value fits in a long
but not an int
. If sizeof(long) == sizeof(int)
, an out of range value will result in errno
being set to non-zero to catch the error, and the INT_MIN
and INT_MAX
cases will never be true.
2
Strictly speaking, it's the ranges ofint
andlong
that are relevant here, not their sizes. In the presence of padding bits, it's possible forint
andlong
to have the same size, but forlong
to have a wider range. (Few if any implementations actually use padding bits, though.)
– Keith Thompson
4 hours ago
if (errno) {
is not a sufficient test to detect "conversion failed" aserrno
can still be 0.
– chux
1 hour ago
add a comment |
You can use strtol
for this. You'll first need to check if this function fails to convert the value. If it convert successfully, then check if the value is in the range of INT_MIN
to INT_MAX
:
errno = 0;
long x = strtol(argv[1], NULL, 10);
if (errno) {
perror("conversion failed");
} else if (x < INT_MIN) {
printf("value too smalln");
} else if (x > INT_MAX) {
printf("value too bign");
} else {
printf("value = %ldn", x);
}
Note that this will work whether long
is the same size as int
or larger.
If sizeof(long) > sizeof(int)
, the INT_MIN
and INT_MAX
checks will catch the cases where the value fits in a long
but not an int
. If sizeof(long) == sizeof(int)
, an out of range value will result in errno
being set to non-zero to catch the error, and the INT_MIN
and INT_MAX
cases will never be true.
2
Strictly speaking, it's the ranges ofint
andlong
that are relevant here, not their sizes. In the presence of padding bits, it's possible forint
andlong
to have the same size, but forlong
to have a wider range. (Few if any implementations actually use padding bits, though.)
– Keith Thompson
4 hours ago
if (errno) {
is not a sufficient test to detect "conversion failed" aserrno
can still be 0.
– chux
1 hour ago
add a comment |
You can use strtol
for this. You'll first need to check if this function fails to convert the value. If it convert successfully, then check if the value is in the range of INT_MIN
to INT_MAX
:
errno = 0;
long x = strtol(argv[1], NULL, 10);
if (errno) {
perror("conversion failed");
} else if (x < INT_MIN) {
printf("value too smalln");
} else if (x > INT_MAX) {
printf("value too bign");
} else {
printf("value = %ldn", x);
}
Note that this will work whether long
is the same size as int
or larger.
If sizeof(long) > sizeof(int)
, the INT_MIN
and INT_MAX
checks will catch the cases where the value fits in a long
but not an int
. If sizeof(long) == sizeof(int)
, an out of range value will result in errno
being set to non-zero to catch the error, and the INT_MIN
and INT_MAX
cases will never be true.
You can use strtol
for this. You'll first need to check if this function fails to convert the value. If it convert successfully, then check if the value is in the range of INT_MIN
to INT_MAX
:
errno = 0;
long x = strtol(argv[1], NULL, 10);
if (errno) {
perror("conversion failed");
} else if (x < INT_MIN) {
printf("value too smalln");
} else if (x > INT_MAX) {
printf("value too bign");
} else {
printf("value = %ldn", x);
}
Note that this will work whether long
is the same size as int
or larger.
If sizeof(long) > sizeof(int)
, the INT_MIN
and INT_MAX
checks will catch the cases where the value fits in a long
but not an int
. If sizeof(long) == sizeof(int)
, an out of range value will result in errno
being set to non-zero to catch the error, and the INT_MIN
and INT_MAX
cases will never be true.
edited 4 hours ago
Keith Thompson
194k26290484
194k26290484
answered 4 hours ago
dbushdbush
103k13108145
103k13108145
2
Strictly speaking, it's the ranges ofint
andlong
that are relevant here, not their sizes. In the presence of padding bits, it's possible forint
andlong
to have the same size, but forlong
to have a wider range. (Few if any implementations actually use padding bits, though.)
– Keith Thompson
4 hours ago
if (errno) {
is not a sufficient test to detect "conversion failed" aserrno
can still be 0.
– chux
1 hour ago
add a comment |
2
Strictly speaking, it's the ranges ofint
andlong
that are relevant here, not their sizes. In the presence of padding bits, it's possible forint
andlong
to have the same size, but forlong
to have a wider range. (Few if any implementations actually use padding bits, though.)
– Keith Thompson
4 hours ago
if (errno) {
is not a sufficient test to detect "conversion failed" aserrno
can still be 0.
– chux
1 hour ago
2
2
Strictly speaking, it's the ranges of
int
and long
that are relevant here, not their sizes. In the presence of padding bits, it's possible for int
and long
to have the same size, but for long
to have a wider range. (Few if any implementations actually use padding bits, though.)– Keith Thompson
4 hours ago
Strictly speaking, it's the ranges of
int
and long
that are relevant here, not their sizes. In the presence of padding bits, it's possible for int
and long
to have the same size, but for long
to have a wider range. (Few if any implementations actually use padding bits, though.)– Keith Thompson
4 hours ago
if (errno) {
is not a sufficient test to detect "conversion failed" as errno
can still be 0.– chux
1 hour ago
if (errno) {
is not a sufficient test to detect "conversion failed" as errno
can still be 0.– chux
1 hour ago
add a comment |
How should I verify that an integer value passed in from argv won't overflow?
Use strtol()
and check the end pointer. Then check errno
and maybe a range test
if (argc > 1) {
char *endptr;
errno = 0;
long num = strtol(argv[1], &endptr, 10);
if (argv[1] == endptr) {
puts("No conversion");
} else if (errno == ERANGE) {
puts("Value outside long range");
#if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
} else if (num < INT_MAX || num > INT_MAX) {
errno = ERANGE;
puts("Value outside int range");
#endif
} else {
// If code wants to look for trailing junk
if (*endptr) {
puts("Non-numeric text");
} else {
printf("Success %dn", (int) num);
}
}
Based on Why is there no strtoi in stdlib.h?
#else
should be#endif
– chqrlie
2 hours ago
@chqrlie Yes, code amended.
– chux
1 hour ago
add a comment |
How should I verify that an integer value passed in from argv won't overflow?
Use strtol()
and check the end pointer. Then check errno
and maybe a range test
if (argc > 1) {
char *endptr;
errno = 0;
long num = strtol(argv[1], &endptr, 10);
if (argv[1] == endptr) {
puts("No conversion");
} else if (errno == ERANGE) {
puts("Value outside long range");
#if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
} else if (num < INT_MAX || num > INT_MAX) {
errno = ERANGE;
puts("Value outside int range");
#endif
} else {
// If code wants to look for trailing junk
if (*endptr) {
puts("Non-numeric text");
} else {
printf("Success %dn", (int) num);
}
}
Based on Why is there no strtoi in stdlib.h?
#else
should be#endif
– chqrlie
2 hours ago
@chqrlie Yes, code amended.
– chux
1 hour ago
add a comment |
How should I verify that an integer value passed in from argv won't overflow?
Use strtol()
and check the end pointer. Then check errno
and maybe a range test
if (argc > 1) {
char *endptr;
errno = 0;
long num = strtol(argv[1], &endptr, 10);
if (argv[1] == endptr) {
puts("No conversion");
} else if (errno == ERANGE) {
puts("Value outside long range");
#if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
} else if (num < INT_MAX || num > INT_MAX) {
errno = ERANGE;
puts("Value outside int range");
#endif
} else {
// If code wants to look for trailing junk
if (*endptr) {
puts("Non-numeric text");
} else {
printf("Success %dn", (int) num);
}
}
Based on Why is there no strtoi in stdlib.h?
How should I verify that an integer value passed in from argv won't overflow?
Use strtol()
and check the end pointer. Then check errno
and maybe a range test
if (argc > 1) {
char *endptr;
errno = 0;
long num = strtol(argv[1], &endptr, 10);
if (argv[1] == endptr) {
puts("No conversion");
} else if (errno == ERANGE) {
puts("Value outside long range");
#if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
} else if (num < INT_MAX || num > INT_MAX) {
errno = ERANGE;
puts("Value outside int range");
#endif
} else {
// If code wants to look for trailing junk
if (*endptr) {
puts("Non-numeric text");
} else {
printf("Success %dn", (int) num);
}
}
Based on Why is there no strtoi in stdlib.h?
edited 1 hour ago
answered 2 hours ago
chuxchux
84.8k874157
84.8k874157
#else
should be#endif
– chqrlie
2 hours ago
@chqrlie Yes, code amended.
– chux
1 hour ago
add a comment |
#else
should be#endif
– chqrlie
2 hours ago
@chqrlie Yes, code amended.
– chux
1 hour ago
#else
should be #endif
– chqrlie
2 hours ago
#else
should be #endif
– chqrlie
2 hours ago
@chqrlie Yes, code amended.
– chux
1 hour ago
@chqrlie Yes, code amended.
– chux
1 hour ago
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55462918%2fhow-should-i-verify-that-an-integer-value-passed-in-from-argv-wont-overflow%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
7
Use
strtol
and compare to INT_MAX/MIN.– Eugene Sh.
4 hours ago
2
if (longvalue > INT_MAX) /* overflow */;
don't forget to#include <limits.h>
– pmg
4 hours ago
1
@pmg check would fail for platforms when
sizeof(int) == sizeof(long) = true
.– SergeyA
4 hours ago
1
@pmg, you can do it in a single check by just comparing for
>= INT_MAX
. This will always work.– SergeyA
4 hours ago
1
@SergeyA Yeah, apparently one should handle
strtol
errors too. I assumed OP is already aware of that when mentioned usingstrtol
.– Eugene Sh.
4 hours ago