So I am having some problems. I am creating a program which calculates the number of primes from 1 to N. It takes input and has 3 inputs:
"e" - exit the program
"p N" - calculate number of primes until N
everything else - print an error message
After "p N" or invalid input the program can still take input even if the calculation isn't finished. This is achieved by completing each calculation in a different thread (i haven't implemented this part yet).
I'm using atoi() to turn the N into an integer variable. And the following problem comes in - for some reason everything after that part of the code doesn't run. So it creates like a breakpoint or something. Everything else after the atoi() line runs after I enter Ctrl+D in the linux terminal and nothing else.
I have no idea why this is caused or how to fix it and my question is should I fix it and how or should I just implement the threads and it will fix itself?
Code:
int fd = 0; // set read() to read from STDIN_FILENO, because it's number is 0
const size_t read_size = 100; // set chunk size
size_t size = read_size;
size_t offset = 0;
size_t res = 0;
char *buff = malloc(size+1);
*buff = '\0';
while((res = read(fd, buff + offset, read_size)) > 0) // read from stdin and save to buff
{
if(buff[offset] == '\n')
{
buff[offset] = '\0';
if(buff[0] == 'e')
{
return 0;
}
else if(buff[0] == 'p' && buff[1] == ' ')
{
memmove(&buff[0], &buff[2], strlen(buff)-1);
int input_num = atoi(buff); // from here on out nothing runs (I tried printing strings, variables and nothing worked)
int prime_count = 0;
for(int i = 2; i < input_num; i++)
{
if(isPrime(i))
{
prime_count++;
}
}
printf("%d", prime_count);
}
else
{
write(STDOUT_FILENO, "Supported commands:\np N - Starts a new calculation for the number of primes from 1 to N\ne - Waits for all calculations to finish and exits\n",
strlen("Supported commands:\np N - Starts a new calculation for the number of primes from 1 to N\ne - Waits for all calculations to finish and exits\n"));
}
// reset the buffer (free its memory and allocate new memory for the next input)
offset = 0;
size = read_size;
free(buff);
buff = NULL;
buff = malloc(size + 1);
*buff = '\0';
}
else
{
offset += res;
buff[offset] = '\0';
if (offset + read_size > size)
{
size *= 2;
buff = realloc(buff, size+1);
}
}
}
free(buff);
buff = NULL;
The result is printed after the input is taken and after ctrl+D.