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

Does Germany produce more waste than the US?

Upgrading From a 9 Speed Sora Derailleur?

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

Do I need to write [sic] when including a quotation with a number less than 10 that isn't written out?

That's an odd coin - I wonder why

Compensation for working overtime on Saturdays

Would a grinding machine be a simple and workable propulsion system for an interplanetary spacecraft?

Why was Sir Cadogan fired?

What difference does it make matching a word with/without a trailing whitespace?

Is the offspring between a demon and a celestial possible? If so what is it called and is it in a book somewhere?

Find the majority element, which appears more than half the time

Masking layers by a vector polygon layer in QGIS

My ex-girlfriend uses my Apple ID to login to her iPad, do I have to give her my Apple ID password to reset it?

Direct Implications Between USA and UK in Event of No-Deal Brexit

pgfplots: How to draw a tangent graph below two others?

Why does freezing point matter when picking cooler ice packs?

How can the PCs determine if an item is a phylactery?

How to pronounce fünf in 45

Ising model simulation

Can Sri Krishna be called 'a person'?

Raspberry pi 3 B with Ubuntu 18.04 server arm64: what pi version

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

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

Why did early computer designers eschew integers?



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

Gersau Kjelder | Navigasjonsmeny46°59′0″N 8°31′0″E46°59′0″N...

Hestehale Innhaldsliste Hestehale på kvinner | Hestehale på menn | Galleri | Sjå òg |...

What is the “three and three hundred thousand syndrome”?Who wrote the book Arena?What five creatures were...