Skip to content

Commit

Permalink
strtol() and related error checking
Browse files Browse the repository at this point in the history
  • Loading branch information
attipaci committed Oct 16, 2024
1 parent bc700f5 commit b2d54c4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
25 changes: 16 additions & 9 deletions src/xchange.c
Original file line number Diff line number Diff line change
Expand Up @@ -316,24 +316,30 @@ int xPrintDims(char *dst, int ndim, const int *sizes) {
* \return Number of valid (i.e. positive) dimensions parsed.
*/
int xParseDims(const char *src, int *sizes) {
static const char *fn = "xParseDims";

int ndim, N = 1;
char *next = (char *) src;

if(!src) return x_error(0, EINVAL, "xParseDims", "'src' is NULL");
if(!src) return x_error(0, EINVAL, fn, "'src' is NULL");
if(!sizes) return 0;

for(ndim = 0; ndim <= X_MAX_DIMS; ) {
char *from = next;

*sizes = strtol(from, &next, 10);
if(next == from) break;
if(errno == ERANGE) break;
errno = 0;
*sizes = (int) strtol(from, &next, 10);
if(next == from) break; // Empty string
if(errno) {
x_error(0, errno, fn, "invalid dimension: %s\n", from);
break;
}

if(*sizes <= 0) continue; // ignore 0 or negative sizes.
if(*sizes <= 0) continue; // ignore 0 or negative sizes.

N *= *sizes;

sizes++; // move to the next dimension
sizes++; // move to the next dimension
ndim++;
}

Expand Down Expand Up @@ -458,11 +464,11 @@ boolean xParseBoolean(char *str, char **end) {
}

/* Try parse as a number... */
errno = 0;
l = strtol(str, end, 0);
if(errno) x_error(FALSE, errno, fn, "invalid argument: %s", str);

if(errno != ERANGE) return (l != 0);

return x_error(FALSE, errno, fn, "invalid argument: %s", str);
return (l != 0);
}


Expand Down Expand Up @@ -529,6 +535,7 @@ double xParseDouble(const char *str, char **tail) {
}
#endif

errno = 0;
return strtod(str, tail);
}

Expand Down
6 changes: 4 additions & 2 deletions src/xjson.c
Original file line number Diff line number Diff line change
Expand Up @@ -592,8 +592,9 @@ static void *ParsePrimitive(char **pos, XType *type, int *lineNumber) {
}

// Try parse as int / long
errno = 0;
ll = strtoll(next, &end, 0);
if(end == *pos) if(errno != ERANGE) {
if(end == *pos && !errno) {
long long *value = (long long *) malloc(sizeof(long));
x_check_alloc(value);
*value = ll;
Expand All @@ -602,8 +603,9 @@ static void *ParsePrimitive(char **pos, XType *type, int *lineNumber) {
}

// Try parse as double...
errno = 0;
d = strtod(next, &end);
if(end == *pos) {
if(end == *pos && !errno) {
double *value = (double *) malloc(sizeof(double));
x_check_alloc(value);
*value = d;
Expand Down

0 comments on commit b2d54c4

Please sign in to comment.