Valgrind invalid write of size 8 - c

I'm experimenting with C structs and I've come up with a invalid write of size 8 followed by invalid read of size 8 messages from valgrind.
My code is only looping through arguments (if argc > 1) and for each filename, it scans for a string and unsigned int indicating name and age(struct player).
This is all the code I've got so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct player {
char name[20];
unsigned int age;
};
struct player *player_new_from_stream(FILE * stream){
struct player *new_player = (struct player*) malloc(sizeof(struct player));
char *p_name = malloc(20);
char *p_age = malloc(20);
if (stream != stdin){
if (fgets(p_name, 20, stream) != NULL){
char *p = strrchr(p_name, '\n');
if (p)
*p = '\0';
strcpy(new_player->name, p_name);
}
if (fgets(p_age, 20, stream) != NULL)
new_player->age = atoi(p_age);
}
else {
printf("enter name and age for a player\n");
gets(p_name);
gets(p_age);
strcpy(new_player->name, p_name);
new_player->age = atoi(p_age);
}
free(p_name);
free(p_age);
return new_player;
}
void player_inspect(struct player plyr, char* prefix){
printf("[%s] name: %s\n", prefix, plyr.name);
printf("[%s] age : %d\n", prefix, plyr.age);
}
int main(int argc, char* argv[]){
FILE * stream;
char* argument;
// below: trying to allocate (argc - 1) pointers
// valgrind's --show-origins=yes points here for both errors
struct player **players = malloc(sizeof(int) * (argc - 1));
int i = 1;
for (; i < argc; i++){
argument = argv[i];
if (strcmp("-", argument) != 0){
if ((stream = fopen(argument, "r")) == NULL) perror("Error opening file");
else {
// the next line emits Invalid write of size 8 in valgrind
players[i-1] = player_new_from_stream(stream);
fclose(stream);
}
} else {
players[i-1] = player_new_from_stream(stdin);
}
}
i = 0;
char buffer[15];
for (; i < argc - 1; i++){
sprintf(buffer, "%d", i);
// the next line emits Invalid read of size 8
player_inspect(*(players[i]), buffer);
free(players[i]);
}
free(players);
return 0;
}
What is wrong here? I want to return a pointer to struct player from player_new_from_stream and pack this pointer to array players in main().

This is wrong:
struct player **players = malloc(sizeof(int) * (argc - 1));
Use this instead:
struct player **players = malloc(sizeof(*players) * (argc - 1));
Note that on your system, sizeof(int) == 4 while sizeof(struct player *) == 8.

I ran it under valgrind with valid input files (player files), compiled with gcc -g and it didn't give any of these invalid read/write messages.
It also worked for using stdin.
However, when I ran it with non-existent files, it had a read error at
i = 0;
char buffer[15];
for (; i < argc - 1; i++){
sprintf(buffer, "%d", i);
player_inspect(*(players[i]), buffer); // <<HERE
free(players[i]);
}
Since the players[i] pointer was NULL due to the pointer at that array index not being set if the fopen call fails.

You need to do double allocation if you want to use array:
struct player **players = malloc(sizeof(struct player*) * (argc - 1));
for (int i=0; i<argc-1;i++)
player[i] = malloc(sizeof(struct player));

Related

Structures not taking values

I'm having an issue with an assignment. The task is to read a string from a txt file and compare it to an array of pointers to structures. If the string already appears then increase the count of that struct by 1, if not found, insert the string into the array with count 1. The struct is defined:
struct wordfreq {
int count;
char *word;
}
Here is the code:
#include <stdio.h>
#include <stdlib.h>
struct wordfreq {
int count;
char *word;
};
typedef struct wordfreq wordfreq;
int mystrcmp(char *str1, char *str2);
int main(int argc, char *argv[])
{
int i, j, flag, current, spot;
char *temp, *temp2;
FILE *infile, *outfile;
wordfreq *wordsptr[1000];
if (argc != 3)
{
printf("Invalid number of arguments, exiting\n");
return 1;
}
else
{
infile = fopen(argv[1], "r");
outfile = fopen(argv[2], "w");
if (infile == NULL)
{
printf("Error opening input file, exiting\n");
return 2;
}
if (outfile == NULL)
{
printf("Error opening output file, exiting\n");
return 3;
}
}
current = 0;
flag = 0;
for (i = 0; i < 1000; i++)
wordsptr[i] = NULL;
temp = (char *)calloc(20,sizeof(char));
while (fgets(temp, 20, infile) != NULL)
{
flag = 0;
for (i = 0; i < 20; i++)
if (temp[i] == '\n')
temp[i] = '\0';
printf("%s %d\n", temp, current);
wordsptr[current] = (wordfreq *)malloc(sizeof(wordfreq));
wordsptr[current]->word = (char *)malloc(20*sizeof(char));
(*wordsptr[current]).word = temp;
(*wordsptr[current]).count = 1;
current++;
}
for (i = 0; i < current; i++)
printf("%d %s\n", (*wordsptr[i]).count, (*wordsptr[i]).word);
free(temp);
for (i = 0; i < 1000; i++)
{
wordsptr[i] = NULL;
free(wordsptr[i]);
}
if (infile != NULL)
fclose(infile);
if (outfile != NULL)
fclose(outfile);
return 0;
}
int mystrcmp(char *str1, char *str2)
{
int i;
for (i = 0; str1[i] != '\0' || str2[i] != '\0';i++)
if (str1[i] != str2[i])
return 1;
return 0;
}
A couple of stipulations:
1) Have to initialize all pointers to null
2) Have to use an array of pointers to structures
run:
./assign6 words.txt freq.txt
words.txt:
apple
orange
apple
orange
banana
banana
The output I'm receiving:
1 banana
1 banana
1 banana
1 banana
1 banana
1 banana
It's supposed to output the count of the string in the txt file and the string itself to the file specified by argv[2]. Please help!
You are assigning the address of temp, which is constantly updated with new values at every iteration, hence why you get the string of the last iteration in all structures here. This is caused by the following lines:
wordsptr[current]->word = (char *)malloc(20*sizeof(char));
(*wordsptr[current]).word = temp;
(Which it is worth mentioning that this is also a memory leak because you lose the pointer to the heap memory.)
You should instead use strcpy() or a similar method to copy the characters from temp to wordsptr[current]->word.

Reading and writing from files with a new form

I'm trying to read from a file and I have to use a new form of it I'm not really certain how to use. I've posted the code below of what function I have and I'm not sure what to do about this error and how to fix it?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
double* read_file(FILE* file, int length);
int main(int argc, char* argv[])
{
double* array = malloc(10 * sizeof(double));
int length = atoi(*(argv + 1));
FILE* file = *(argv + 2);
if (argc < 4 || argc > 4)
{
printf("Insufficient arguments. Check your command line.\n");
return 0;
}
array = read_file(file, length);
printf("%p", array);
return 0;
}
double* read_file (FILE* file, int length)
{
FILE* ptr;
double* array = malloc(length * sizeof(double));
int i = 0;
if ((ptr = fopen(file, "r")) == NULL)
{
return 0;
}
else
{
for (i = 0; i < length; i++)
{
fscanf(ptr, "%lf", (array + i));
}
}
fclose(ptr);
return array;
}
First of all, you're trying to assign a char string to a variable of type pointer to FILE. The compiler won't let you do that.
// not allowed
FILE* file = *(argv + 2);
Secondly, you're passing a pointer to FILE to fopen(), but fopen() expects it's first argument to be a char string so that won't work either.
// file is FILE*, not allowed
ptr = fopen(file, "r"));
If you fix those two lines the code should compile.
fix like this
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//double* read_file(FILE* file, int length);
//You do not need to pass a file pointer, you need a file name.
//It opens the file within this function
double *read_file(const char *filename, int length);
int main(int argc, char* argv[]){
//if (argc < 4 || argc > 4)
//argc < 4 || argc > 4 same as argc != 4
//It is thought that it is 3 because only argv[1] and argv[2] are used.
//It is necessary to check arguments before using them.
if (argc != 3) {
printf("Usage : %s number_of_elements file_name\n", argv[0]);
printf("Insufficient arguments. Check your command line.\n");
return 0;
}
//double* array = malloc(10 * sizeof(double));//It is not necessary as it is secured by read_file. Make memory leak.
int length = atoi(argv[1]);
const char *file = argv[2];
double *array = read_file(file, length);
if(array != NULL){
for(int i = 0; i < length; ++i)
printf("%f\n", array[i]);
free(array);
}
return 0;
}
double* read_file (const char *file, int length){
FILE *ptr;
if ((ptr = fopen(file, "r")) == NULL){
return NULL;
}
//It causes a memory leak unless you first confirm that the file can be opened
double *array = malloc(length * sizeof(double));
for (int i = 0; i < length; i++){
if(1 != fscanf(ptr, "%lf", array + i)){
printf("Failed to read the %ith element.\n", i+1);
break;
}
}
fclose(ptr);
return array;
}

Reading lines from file

I am trying to read strings and integers from a simple text file to my array. But the problem is that I get some random characters in a line in the middle of my list. It probably has to do with a newline problem, but I am not sure. The text file looks like this:
4
Mr Tambourine Man
Bob Dylan
1965
Dead Ringer for Love
Meat Loaf
1981
Euphoria
Loreen
2012
Love Me Now
John Legend
2016
The first number (4), indicates how many songs there are in the list. I have made a struct which will be able to hold the songs and dynamically allocate memory for each pointer.
Struct:
typedef struct Song {
char *song;
char *artist;
int *year;
} Song;
Allocated:
Song *arr;
arr = (Song*)malloc(sizeof(Song));
Function:
int loadFile(char fileName[], Song *arr, int nrOf) {
FILE *input = fopen(fileName, "r");
if (input == NULL) {
printf("Error, the file could not load!\n");
} else {
int i = 0;
fscanf(input, "%d\n", &nrOf);
for (int i = 0; i < nrOf; i++) {
arr[i].song = (char*)malloc(sizeof(char));
arr[i].artist = (char*)malloc(sizeof(char));
arr[i].year = (int*)malloc(sizeof(int));
fgets(arr[i].song, 100, input);
fgets(arr[i].artist, 100, input);
fscanf(input, "%d\n", arr[i].year);
}
printf("The file is now ready.\n");
fclose(input);
}
return nrOf;
}
Are you able to find the problem? Or do you have a better solution?
This is wrong:
arr[i].song = (char*)malloc(sizeof(char));
arr[i].artist = (char*)malloc(sizeof(char));
You are only allocating buffers of size 1, there's no scaling. This gives you undefined behavior when you overrun the buffers by loading more data into them than they can hold.
I would expect those to read:
arr[i].song = malloc(100);
and so on. Note that no cast is necessary, and sizeof (char) is always 1.
Also, this:
arr[i].year = (int*)malloc(sizeof(int));
is super-strange. There's absolutely no reason to dynamically allocate a single integer, just make the field an int and store the value there directly.
First Issue:
arr[i].song = (char*)malloc(sizeof(char));
arr[i].artist = (char*)malloc(sizeof(char));
Are only allocating 1 byte for your char* pointers, song and artist. You can allocate a size for this:
arr[i].song = (char*)malloc(100 * sizeof(char)); /* or malloc(100) */
arr[i].artist = (char*)malloc(100 * sizeof(char));
Or you can simply malloc() enough space from you buffer:
char buffer[100];
fgets(buffer, 100, input);
/* check for failure, remove newline */
arr[i].song = malloc(strlen(buffer)+1);
/* check error from malloc */
strcpy(arr[i].song, buffer);
Or even use strdup():
arr[i].song = strdup(buffer);
Which is a substitute for malloc()/strcpy().
Note: You can also read Do I cast the result of malloc?.
Second Issue:
Your current struct:
typedef struct Song {
char *song;
char *artist;
int *year;
} Song;
Can be simplified to:
typedef struct {
char *song;
char *artist;
int year;
} Song;
Because year does not need to be a pointer. Easier to manage if its just an int. This avoids having to do allocations like:
arr[i].year = (int*)malloc(sizeof(int));
Other Recommendations:
You should check the return of fscanf() and fgets() as its safe to do this. It helps just incase your file will have incorrect data. This goes the same for malloc(), which can return NULL is unsuccessfully allocated on the heap.
Here is some code with the above considerations in mind:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 100
typedef struct {
char *song;
char *artist;
int year;
} Song;
Song *create_array(FILE *input, int *nrof);
void load_data(Song *arr, FILE *input, int nrof);
void print_free_data(Song *arr, int nrof);
void get_buffer(char buffer[], FILE *input);
int main(void) {
FILE *input;
Song *arr;
int nrof;
input = fopen("artist.txt", "r");
if (input == NULL) {
fprintf(stderr, "Error reading file\n");
exit(EXIT_FAILURE);
}
arr = create_array(input, &nrof);
load_data(arr, input, nrof);
print_free_data(arr, nrof);
fclose(input);
return 0;
}
Song *create_array(FILE *input, int *nrof) {
Song *arr;
if (fscanf(input, "%d ", nrof) != 1) {
fprintf(stderr, "Cannot find number of songs\n");
exit(EXIT_FAILURE);
}
arr = malloc(*nrof * sizeof(*arr));
if (arr == NULL) {
fprintf(stderr, "Cannot allocate %d spaces for array\n", *nrof);
exit(EXIT_FAILURE);
}
return arr;
}
void load_data(Song *arr, FILE *input, int nrof) {
char buffer[SIZE];
for (int i = 0; i < nrof; i++) {
get_buffer(buffer, input);
arr[i].song = malloc(strlen(buffer)+1);
if (arr[i].song == NULL) {
fprintf(stderr, "Cannot allocate song\n");
exit(EXIT_FAILURE);
}
strcpy(arr[i].song, buffer);
get_buffer(buffer, input);
arr[i].artist = malloc(strlen(buffer)+1);
if (arr[i].artist == NULL) {
fprintf(stderr, "Cannot allocate artist\n");
exit(EXIT_FAILURE);
}
strcpy(arr[i].artist, buffer);
if (fscanf(input, "%d ", &arr[i].year) != 1) {
fprintf(stderr, "Cannot find year for Song: %s Album: %s\n",
arr[i].song, arr[i].artist);
exit(EXIT_FAILURE);
}
}
}
void get_buffer(char buffer[], FILE *input) {
size_t slen;
if (fgets(buffer, SIZE, input) == NULL) {
fprintf(stderr, "Error from fgets(), line not read\n");
exit(EXIT_FAILURE);
}
slen = strlen(buffer);
if (slen > 0 && buffer[slen-1] == '\n') {
buffer[slen-1] = '\0';
} else {
fprintf(stderr, "Too many characters entered\n");
exit(EXIT_FAILURE);
}
}
void print_free_data(Song *arr, int nrof) {
for (int i = 0; i < nrof; i++) {
printf("%s\n%s\n%d\n\n", arr[i].song, arr[i].artist, arr[i].year);
free(arr[i].song);
arr[i].song = NULL;
free(arr[i].artist);
arr[i].artist = NULL;
}
free(arr);
arr = NULL;
}
Which Outputs correct data:
Mr Tambourine Man
Bob Dylan
1965
Dead Ringer for Love
Meat Loaf
1981
Euphoria
Loreen
2012
Love Me Now
John Legend
2016
Your memory allocation is incorrect. The structure should have char arrays for the song and artist names and an int for the year, and you should modify your API to return the array and its size to the caller:
int loadFile(const char *fileName, Song **arr, int *numberp);
Here is a corrected and simplified of your program:
#include <stdio.h>
#include <stdlib.h>
typedef struct Song {
char song[100];
char artist[100];
int year;
} Song;
/* call as
if (loadFile(fileName, &songs, &songs_size) < 0) {
// deal with error...
}
*/
int loadFile(const char *fileName, Song **arrp, int *numberp) {
FILE *input;
Song *arr;
int i, nrOf;
input = fopen(fileName, "r");
if (input == NULL) {
fprintf(stderr, "Cannot open file %s\n", filename);
return -1;
} else {
if (fscanf(input, "%d\n", &nrOf) != 1) {
fprintf(stderr, "%s: missing number of items\n", filename);
fclose(intput);
return -1;
}
arr = calloc(sizeof(*arr), nrOf);
if (arr == NULL) {
fprintf(stderr, "cannot allocate memory for %d items\n", nrOf);
fclose(intput);
return -1;
}
for (int i = 0; i < nrOf; i++) {
char cc;
if (fscanf(input, "%99[^\n]%*c%99[^\n]%*c%d%c",
sarr[i].song, arr[i].artist,
&arr[i].year, &cc) != 4 || cc != '\n') {
fprintf(stderr, "%s: invalid format for item %d\n",
filename, i);
break;
}
}
printf("The file is now ready.\n");
fclose(input);
*arrp = arr;
*numberp = i;
return i;
}
}

struct pointers to same memory address producing different data?

I have this simple code to read the lines of a file and store them in a struct:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct filedata {
char **items;
int lines;
};
struct filedata *read_file(char *filename) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Can't read %s \n", filename);
exit(1);
}
char rbuff;
int nlines = 0; // amount of lines
int chr = 0; // character count
int maxlen = 0; // max line length (to create optimal buffer)
int minlen = 2; // min line length (ignores empty lines with just \n, etc)
while ((rbuff = fgetc(file) - 0) != EOF) {
if (rbuff == '\n') {
if (chr > maxlen) {
maxlen = chr + 1;
}
if (chr > minlen) {
nlines++;
}
chr = 0;
}
else {
chr++;
}
}
struct filedata *rdata = malloc(sizeof(struct filedata));
rdata->lines = nlines;
printf("lines: %d\nmax string len: %d\n\n", nlines, maxlen);
rewind(file);
char *list[nlines];
int buffsize = maxlen * sizeof(char);
char buff[buffsize];
int i = 0;
while (fgets(buff, buffsize, file)) {
if (strlen(buff) > minlen) {
list[i] = malloc(strlen(buff) * sizeof(char) + 1);
strcpy(list[i], buff);
i++;
}
}
rdata->items = (char **)list;
fclose(file);
int c = 0;
for (c; c < rdata->lines; c++) {
printf("line %d: %s\n", c + 1, rdata->items[c]);
}
printf("\n");
return rdata;
}
int main(void) {
char fname[] = "test.txt";
struct filedata *ptr = read_file(fname);
int c = 0;
for (c; c < ptr->lines; c++) {
printf("line %d: %s\n", c + 1, ptr->items[c]);
}
return 0;
}
This is the output when I run it:
lines: 2
max string len: 6
line 1: hello
line 2: world
line 1: hello
line 2: H��
For some reason when it reaches the second index in ptr->items, it prints gibberish output. But yet, if I throw some printf()'s in there to show the pointer addresses, they're exactly the same.
Valgrind also prints this when iterating over the char array the second time:
==3777== Invalid read of size 8
==3777== at 0x400AB3: main (test.c:81)
==3777== Address 0xfff000540 is on thread 1's stack
==3777== 240 bytes below stack pointer
But that really doesn't give me any clues in this case.
I'm using gcc 4.9.4 with glibc-2.24 if that matters.
list is an non-static local variable and using it after exiting its scope (returning from read_file in this case) will invoke undefined behavior because it will vanish on exiting its scope. Allocate it dynamically (typically on the heap) like
char **list = malloc(sizeof(char*) * nlines);
Adding code to check if malloc()s are successful will make your code better.
The variable list is local to read_file, but you store a pointer to list in rdata->items. When read_file returns, rdata->items is a dangling pointer, and accessing it is undefined behavior.

C Program Segmentation Fault main()

I am novice to C programming and I have written a code to a requirement specification but I am consistently getting Segmentation Fault and unable to proceed ahead.
If the file name is 'code.c' and it runs with an error of not passing the argument (filename). But if the filename is passed, we land in Segmentation Fault.
Any help/suggestions will be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
struct _data
{
char *firstName;
char *lastName;
long number;
};
// SCAN FILE
int SCAN(FILE *(*stream))
{
*stream = fopen("inputFile.data", "r");
int ch = 0, lines = 0;
while (!feof(*stream))
{
ch = fgetc(*stream);
if (ch == '\n')
{
lines++;
}
}
return lines;
}
// LOAD FILE
struct _data *LOAD(FILE *stream, int size)
{
int i;
size_t chrCount;
char *text, *number, *firstName, *lastName;
struct _data *BlackBox;
if ((BlackBox = (struct _data*)calloc(size, sizeof(struct _data))) == NULL)
{
printf("ERROR - Could not allocate memory.\n");
exit(0);
}
rewind(stream);
for (i = 0; i < size; i++)
{
getline(&text, &chrCount, stream);
firstName = strtok(text, " ");
lastName = strtok(text, " ");
number = strtok(NULL, "\n");
// Allocate memory for name part of struct.
if ((BlackBox[i].firstName = (char*)calloc(strlen(firstName), sizeof(char))) == NULL)
{
printf("ERROR - Could not allocate memory.\n");
exit(0);
}
if ((BlackBox[i].lastName = (char*)calloc(strlen(lastName), sizeof(char))) == NULL)
{
printf("ERROR - Could not allocate memory.\n");
exit(0);
}
strcpy(BlackBox[i].firstName, firstName);
strcpy(BlackBox[i].lastName, lastName);
BlackBox[i].number = atol(number);
}
fclose(stream);
return BlackBox;
}
void SEARCH(struct _data *BlackBox, char *name, int size, int inputs)
{
int i;
int found = 0;
char *search = " ";
char *firstName;
char *lastName;
if (inputs == 2)
{
firstName = strtok(name, search);
lastName = strtok(NULL, search);
}
printf("*******************************************\n");
if (inputs == 2)
{
for (i = 0; i < size; i++)
{
if (!strcasecmp(firstName, BlackBox[i].firstName) && !strcasecmp(firstName, BlackBox[i].firstName))
{
printf("The name was found at the %d entry.\n", i);
found = 1;
break;
}
}
}
else
{
for (i = 0; i < size; i++)
{
if (!strcasecmp(firstName, BlackBox[i].firstName) || !strcasecmp(firstName, BlackBox[i].firstName))
{
printf("The name was found at the %d entry.\n", i);
found = 1;
break;
}
}
}
if (found == 0)
{
printf("The name was NOT found.\n");
}
printf("*******************************************\n");
}
// FREE MEMORY
void FREE(struct _data *BlackBox, int size)
{
int i;
for (i = 0; i < size; i++)
{
free(BlackBox[i].firstName);
free(BlackBox[i].lastName);
}
free(BlackBox);
BlackBox = NULL;
}
// MAIN
int main(int argv, char **argc)
{
int size;
FILE *stream;
struct _data *BlackBox;
// argv == 1 WORKS, Below message is printed.
if (argv == 1)
{
printf("*******************************************\n");
printf("* You must include a name to search for. *\n");
printf("*******************************************\n");
}
// argv == 2 DOES NOT WORK, Segmentation Fault.
if (argv == 2)
{
size = SCAN (&stream);
BlackBox = LOAD(stream, size);
SEARCH(BlackBox, argc[1], size, 1);
}
if (argv == 3)
{
size = SCAN(&stream);
BlackBox = LOAD(stream, size);
SEARCH(BlackBox, argc[2], size, 2);
}
return 0;
}
You have a problem in this code:
firstName = strtok(text, " ");
lastName = strtok(text, " ");
number = strtok(NULL, "\n");
...
BlackBox[i].number = atol(number);
The second strtok() call should pass NULL as its first argument. As it is, the third strtok() call is certain to return NULL because the first call modifies text in such a way that the second consumes the whole thing (when tokenizing again from the beginning, as it erroneously does). You do not test for that, however, and as a result, atol() attempts to dereference a null pointer.
Update:
Additionally, as #chqrlie and later #JamesWilkins observed, you do not allocate sufficient space for BlackBox[i].firstName and BlackBox[i].lastName, as you need room for the string terminators as well. This is an entirely separate problem that could also produce a segfault. I like #chqrlie's suggestion to switch to strdup(), but it would be sufficient to just increase each allocation by one unit.
Update 2:
Furthermore, you have an issue with this line:
getline(&text, &chrCount, stream);
You do not initialize variable text before the first call, so it contains a junk value. The function allocates a buffer only when its first argument points to a NULL pointer; otherwise it writes the line to the buffer pointed to by the pointer obtained by dereferencing the first argument. Writing to a random location in memory certainly produces undefined behavior, which in practice often manifests as a segfault.
Moreover, unless you can rely on no line of the file being longer than the first, you also need to free the text pointer at the end of each loop iteration AND reset its value to NULL, so that getline() allocates a fresh buffer on the next iteration. If you do not free it on each iteration, then you need instead to free it after the end of the loop; else you will leak memory.
Try this (though I'm using Visual Studio on Windows). I added code to check for a missing '\n' on the last line, and also allowed for a variable number of search terms. I also increased the memory allocation for strings by 1 to account for the null terminating character. I noticed you are using getline(const char*..., which I think is GNU (Linux?), so I change that to fgets() just so I could compile and test it in VS (so you can change it back if you like). I put in various null checks as well, to be safer.
#include <iostream>
using namespace std;
struct _data
{
char *firstName;
char *lastName;
long number;
};
// SCAN FILE
int SCAN(FILE *(*stream))
{
*stream = fopen("inputFile.data", "r");
if (*stream == NULL)
{
perror("Error opening file");
return 0;
}
char ch = 0, lines = 0, linesize = 0;
while ((ch = fgetc(*stream)) != EOF)
{
if (ch == '\n')
{
lines++;
linesize = 0;
}
else linesize++;
}
if (linesize > 0)
lines++; // (last line doesn't have '\n')
return lines;
}
// LOAD FILE
struct _data *LOAD(FILE *stream, int lineCount)
{
int i;
size_t chrCount = 256;
char text[256], *result, *number, *firstName, *lastName;
struct _data *BlackBox;
if ((BlackBox = (struct _data*)calloc(lineCount, sizeof(struct _data))) == NULL)
{
printf("ERROR - Could not allocate memory.\n");
exit(0);
}
else memset(BlackBox, 0, sizeof(struct _data) * lineCount); // (make sure all data members are null to begin)
rewind(stream);
for (i = 0; i < lineCount; i++)
{
result = fgets(text, chrCount, stream);
if (result == NULL)
break; // (EOF)
firstName = strtok(text, " ");
lastName = strtok(NULL, " ");
number = strtok(NULL, "\n");
// Allocate memory for name part of struct.
if ((BlackBox[i].firstName = (char*)calloc(strlen(firstName) + 1, sizeof(char))) == NULL)
{
printf("ERROR - Could not allocate memory.\n");
exit(0);
}
if ((BlackBox[i].lastName = (char*)calloc(strlen(lastName) + 1, sizeof(char))) == NULL)
{
printf("ERROR - Could not allocate memory.\n");
exit(0);
}
strcpy(BlackBox[i].firstName, firstName);
strcpy(BlackBox[i].lastName, lastName);
BlackBox[i].number = atol(number);
}
fclose(stream);
return BlackBox;
}
void SEARCH(struct _data *BlackBox, char **names, int lineCount, int inputs)
{
int i, l;
int found = 0;
printf("*******************************************\n");
for (i = 0; i < inputs; ++i)
{
for (l = 0; l < lineCount; ++l)
{
if (BlackBox[l].firstName != NULL && !_stricmp(names[i], BlackBox[l].firstName)
|| BlackBox[l].lastName != NULL && !_stricmp(names[i], BlackBox[l].lastName))
{
printf("The name was found on line %d.\n", 1 + l);
found = 1;
break;
}
}
if (found) break;
}
if (!found)
printf("The name was NOT found.\n");
printf("*******************************************\n");
}
// FREE MEMORY
void FREE(struct _data *BlackBox, int lineCount)
{
int i;
for (i = 0; i < lineCount; i++)
{
if (BlackBox[i].firstName != NULL)
free(BlackBox[i].firstName);
if (BlackBox[i].lastName != NULL)
free(BlackBox[i].lastName);
}
free(BlackBox);
}
// MAIN
int main(int argc, char **argv)
{
int lineCount;
FILE *stream;
struct _data *BlackBox;
// argc == 1 WORKS, Below message is printed.
if (argc == 1)
{
printf("*******************************************\n");
printf("* You must include a name to search for. *\n");
printf("*******************************************\n");
}
// argc == 2 DOES NOT WORK, Segmentation Fault.
if (argc > 1)
{
lineCount = SCAN(&stream);
if (lineCount > 0)
{
BlackBox = LOAD(stream, lineCount);
SEARCH(BlackBox, argv + 1, lineCount, argc - 1);
FREE(BlackBox, lineCount);
}
}
return 0;
}
Tested it on the command line, and it works.
The problem is the argv and argc. argc is supposed to be an int (think argument count), while argv is meant to be char**. You have them mixed up in your main.

Resources