Skip to content

Instantly share code, notes, and snippets.

@reporter123
Created February 17, 2018 03:19
Show Gist options
  • Save reporter123/e8eba8262fa22c6f10182bbfb181a52a to your computer and use it in GitHub Desktop.
Save reporter123/e8eba8262fa22c6f10182bbfb181a52a to your computer and use it in GitHub Desktop.
strtol with a lenght limit.
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;
}
@reporter123
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment