How should I verify that an integer value passed in from argv won't overflow? The Next CEO of...

Airship steam engine room - problems and conflict

Could you use a laser beam as a modulated carrier wave for radio signal?

Prodigo = pro + ago?

Incomplete cube

My boss doesn't want me to have a side project

Are British MPs missing the point, with these 'Indicative Votes'?

What happens if you break a law in another country outside of that country?

Horror film about a man brought out of cryogenic suspension without a soul, around 1990

Simplify trigonometric expression using trigonometric identities

Compensation for working overtime on Saturdays

Mathematica command that allows it to read my intentions

Why doesn't Shulchan Aruch include the laws of destroying fruit trees?

Cannot restore registry to default in Windows 10?

Could a dragon use its wings to swim?

Why can't we say "I have been having a dog"?

Create custom note boxes

Why did the Drakh emissary look so blurred in S04:E11 "Lines of Communication"?

How to unfasten electrical subpanel attached with ramset

How exploitable/balanced is this homebrew spell: Spell Permanency?

Read/write a pipe-delimited file line by line with some simple text manipulation

Find a path from s to t using as few red nodes as possible

Is a distribution that is normal, but highly skewed, considered Gaussian?

How to show a landlord what we have in savings?

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact



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?












6















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?










share|improve this question


















  • 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 using strtol.

    – Eugene Sh.
    4 hours ago
















6















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?










share|improve this question


















  • 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 using strtol.

    – Eugene Sh.
    4 hours ago














6












6








6


0






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?










share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 4 hours ago









JakeJake

109212




109212








  • 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 using strtol.

    – Eugene Sh.
    4 hours ago














  • 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 using strtol.

    – 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












2 Answers
2






active

oldest

votes


















5














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.






share|improve this answer





















  • 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











  • if (errno) { is not a sufficient test to detect "conversion failed" as errno can still be 0.

    – chux
    1 hour ago



















1















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?






share|improve this answer


























  • #else should be #endif

    – chqrlie
    2 hours ago











  • @chqrlie Yes, code amended.

    – chux
    1 hour ago












Your Answer






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
});


}
});














draft saved

draft discarded


















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









5














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.






share|improve this answer





















  • 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











  • if (errno) { is not a sufficient test to detect "conversion failed" as errno can still be 0.

    – chux
    1 hour ago
















5














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.






share|improve this answer





















  • 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











  • if (errno) { is not a sufficient test to detect "conversion failed" as errno can still be 0.

    – chux
    1 hour ago














5












5








5







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.






share|improve this answer















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.







share|improve this answer














share|improve this answer



share|improve this answer








edited 4 hours ago









Keith Thompson

194k26290484




194k26290484










answered 4 hours ago









dbushdbush

103k13108145




103k13108145








  • 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











  • if (errno) { is not a sufficient test to detect "conversion failed" as errno can still be 0.

    – chux
    1 hour ago














  • 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











  • if (errno) { is not a sufficient test to detect "conversion failed" as errno 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













1















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?






share|improve this answer


























  • #else should be #endif

    – chqrlie
    2 hours ago











  • @chqrlie Yes, code amended.

    – chux
    1 hour ago
















1















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?






share|improve this answer


























  • #else should be #endif

    – chqrlie
    2 hours ago











  • @chqrlie Yes, code amended.

    – chux
    1 hour ago














1












1








1








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?






share|improve this answer
















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?







share|improve this answer














share|improve this answer



share|improve this answer








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



















  • #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


















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Щит и меч (фильм) Содержание Названия серий | Сюжет |...

Венесуэла на летних Олимпийских играх 2000 Содержание Состав...

Meter-Bus Содержание Параметры шины | Стандартизация |...