I have to create a function that takes a string and detects if it is a valid ISBN number. In my test code, it works fine but in the official test code that my instructor provided, I get a segmentation fault. Checking the core dump, it appears to be an issue with strlen() on line 14 of my code
#include <iostream>
#include <cstdio>
#include <cstring>
usingnamespace std;
#include "ISBN.h"
#include "ISBNPrefix.h"
int isValid(constchar str[])
{
int check = 0, i, num[10], val = 0, mod = 1;
if (strlen(str) == 10) //10 characters in the string
{
check = 1;
for (i = 0; i < 9; i++) //go through first 9 characters, make sure they're a digit. If they are valid, propagate num array with numerical values
{
if (str[i] < '0' || str[i] > '9')
check = 0;
else
num[i] = str[i] - '0';
}
if (check != 0) //the first 9 characters are digits, make sure 10th char is either a digit or letter X (10). Propagate 10th num array position with numerical value.
{
if (str[9] < '0' || str[9] > '9' && str[9] != 'X')
check = 0;
elseif (str[9] == 'X')
num[9] = 10;
else
num[9] = str[9] - '0';
}
if (check != 0) //do the math to make sure it's all modulo 11
{
for (i = 0; i < 10; i++)
{
val += num[i] * (10 - i);
}
mod = val % 11;
if (mod != 0)
check = 0;
}
} // if statement about there being 10 characters
return check;
}
Here's the part of the main file generating the error:
1 2 3 4 5 6
// test valid
if(isValid(NULL) != 0) {
failed("valid(NULL) did not return false", ++testNumber, &ok,
totalTested);
} else
passed("valid(NULL)", ++testNumber, totalPassed, totalTested);
failed() and passed() are built in functions by the prof that he defined, not me. If I comment out this section, it continues on until I get another segmentation fault later on that also has to do with testing for NULL in another function.
For the heck of it, here's the code for them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* passed displays passing message, increments *totalPassed and *total
* i holds test number
*/
void passed(constchar* message, int i, int* totalPassed, int* total) {
if (DEBUG && message[0] != '\0')
printf("Passed test %4d (%s)\n", i, message);
++*totalPassed;
++*total;
}
/* failed displays failure message, resets *ok to false, increments *total
* i holds test number
*/
void failed(constchar* message, int i, bool* ok, int* total) {
printf("Failed test %4d (%s)\n", i, message);
*ok = false;
++*total;
}