I want to pipe an input to my program that only accepts lines that are valid for my regular expression, i.e. a number of max length 3, followed by at least one white space character, followed by a negative or positive number of max length 7.
The following call
echo -e '1 1\n1 1\x00junk' | ./myProgram
gets through my regular expression but shouldn't.
I guess its cause of getline(), that my regular expression only gets the content in front of the null-terminating byte and ignores everything after.
Is there a way to check for the content after a null-terminating byte without potentially violating the access of the allocated memory of my string, so that the given call ends in an error ?
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <errno.h>
int main() {
int reg;
regex_t regex;
char *regexStr = "^[0-9]{1,3} +-?[0-9]{1,7}(\n|\r|\r\n|0a|0d0a)?$";
int size = 16;
char *buffer = malloc(size * sizeof(char));
size_t len = size;
ssize_t nread;
if (regcomp(®ex, regexStr, REG_EXTENDED)) {
fprintf(stderr, "Couldn't compile regular expression.\n");
return -1;
}
while ((nread = getline(&buffer, &len, stdin)) != EOF) {
if (errno == ENOMEM) { // error if getline() couldnt allocate buffer
fprintf(stderr, "Couldn't allocate enough memory.\n");
return -1;
}
reg = regexec(®ex, buffer, 0, NULL, 0);
if (reg == REG_NOMATCH) { //input invalid if regular expression doesnt match with line
fprintf(stderr, "Input invalid.\n");
return -1;
}
printf("%s", buffer);
}
printf("\n");
printf("Input was valid.\n");
return 0;
}