Created
February 17, 2018 03:19
-
-
Save reporter123/e8eba8262fa22c6f10182bbfb181a52a to your computer and use it in GitHub Desktop.
strtol with a lenght limit.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
long nstrtol(const char *string, size_t len) | |
{ | |
long sig = 1; | |
long value = 0; | |
size_t i = 0; | |
if(string[0] == '-') | |
sign *= -1, i++; | |
for(; len > 0 && isdigit(string[i]); i++, len--) | |
{ | |
value *= 10; | |
value += *string - '0'; | |
if(string[i] == 0) break; | |
} | |
return sign * value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refined from a rough outline on stack overflow. This function reads a string until len bytes or null is reached. This is helpful if dealing with untrusted content such as environment variables. Which could be literally anything like one fallowed by a million zeros. Or something more sinister.