As part of an exercise, I am developing a small grep-like program in C which is supposed to receive a string and some file names in order to look for that string in the referred files.
I got it working by hardcoding the name of the file and the string:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int searchString(char *str1, char *str2) {
if (strstr(str1, str2) == NULL) {
return 0;
} else {
return 1;
}
}
void searchInFile(char *filename, char *str) {
FILE *f;
int lineno =0;
size_t len;
char *buffer;
f = fopen(filename, "r");
if (f != NULL) {
while (getline(&buffer, &len, f) != -1) {
lineno++;
if (searchString(buffer, str)) {
printf("[%s:%d] %s", filename, lineno, buffer);
}
}
}
fclose(f);
}
int main() {
searchInFile("loremipsum.txt", "dolor");
return 0;
}
But as soon as I modify the code to chage the int main() line to add argc and argv, compile it and then run it, the script returns an error message. The modification is:
int main(int argc, char *argv[]) {
searchInFile("loremipsum.txt", "dolor");
return 0;
}
The received error:
* Error in `./a.out': realloc(): invalid pointer: 0x000056424999394d *
Anyone knows why am I getting this error?