In C, I am trying to implement a function that uses getline() to read all the lines from a file. It is implemented similarly to getline(), specifically the fact that it is using realloc() to resize a char** if there is not enough memory allocated to store the next pointer to a line. Unfortunately I am getting seg faults during the string dupilcation process.
After a little poking around, I discovered that the segfault happens during the second iteration while attempting to store the second line in the char pointer array.
ssize_t fgetlines(char*** linesptr, size_t* n, FILE* fp)
{
char* line = NULL;
size_t sz_line = 0;
size_t cur_len = 0;
size_t needed;
if (linesptr == NULL || n == NULL) {
errno = EINVAL;
return -1;
}
if (*linesptr == NULL) {
if (*n == 0)
*n = sizeof(**linesptr) * 30; /* assume 30 lines */
*linesptr = malloc(*n);
if (*linesptr == NULL) {
*n = 0;
return -1;
}
}
while (getline(&line, &sz_line, fp) > 0) {
needed = (cur_len + 1) * sizeof(**linesptr);
while (needed > *n) {
char** new_linesptr;
*n *= 2;
new_linesptr = realloc(*linesptr, *n);
if (new_linesptr == NULL) {
*n /= 2;
free(line);
return -1;
}
*linesptr = new_linesptr;
}
*linesptr[cur_len] = strdup(line);
printf("%s", *linesptr[cur_len]);
if (*linesptr[cur_len] == NULL) {
free(line);
free(*linesptr);
return -1;
}
++cur_len;
}
free(line);
return cur_len;
}
And I call the function like so:
char **settings = NULL;
size_t sz_settings = sizeof(*settings) * 6;
int count = fgetlines(&settings, &sz_settings, f_cfg);
Due to the function not being able to successfully complete I do not get any output. But after printing back the string after strdup() I managed to get one line of f_cfg, "Hello World" before a seg fault.
Should change
*linesptr[cur_len] => (*linesptr)[cur_len]
The modified function is as follows:
ssize_t fgetlines(char *** linesptr, size_t *n, FILE *fp)
{
char *line = NULL;
size_t sz_line = 0;
size_t cur_len = 0;
size_t needed;
if (linesptr == NULL || n == NULL) {
errno = EINVAL;
return -1;
}
if (*linesptr == NULL) {
if (*n == 0)
*n = sizeof(**linesptr) * 30; /* assume 30 lines */
*linesptr = malloc(*n);
if (*linesptr == NULL) {
*n = 0;
return -1;
}
}
while (getline(&line, &sz_line, fp) > 0) {
needed = (cur_len + 1) * sizeof(**linesptr);
while (needed > *n) {
char **new_linesptr;
*n *= 2;
new_linesptr = realloc(*linesptr, *n);
if (new_linesptr == NULL) {
*n /= 2;
free(line);
return -1; // Possible memory leak
}
*linesptr = new_linesptr;
}
(*linesptr)[cur_len] = strdup(line);
printf("%s", (*linesptr)[cur_len]);
if ((*linesptr)[cur_len] == NULL) {
free(line);
free(*linesptr);
return -1; // Possible memory leak
}
++cur_len;
}
free(line);
return cur_len;
}
In addition, when your memory allocation fails, the memory of "strdup" is not free, which will lead to memory leak.
As chux pointed out, the intended precedence here was incorrect. References to *linesptr[cur_len] must be changed to (*linesptr[cur_len]). Also the code hole *n == 0 and *n *= 2 has been fixed.
Related
I'm somehow having troubles creating a dynamic array of strings in C. I'm not getting the expected results and I want to know why ?
readLine() function will read each line seperately and will do some changes if necessary :
char *readLine(FILE *f, size_t *len)
{
char *line = NULL;
ssize_t nread;
if (f == NULL)
{
return NULL;
}
if ((nread = getline(&line, len, f)) != -1)
{
if (line[nread - 1] == '\n')
{
line[strlen(line)-1] = '\0';
*len = strlen(line);
}
return line;
}
else
{
return NULL;
}
}
readFile() function will return an array of strings after reading all of the lines using readLine and then storing them into an array of strings :
char **readFile(const char *filename, size_t *fileLen)
{
char *result;
int idx = 0;
char **array = calloc(1, sizeof(char*) );
if (filename == NULL || fileLen == NULL)
{
return NULL;
}
FILE *f = fopen(filename, "r");
if (f == NULL)
{
return NULL;
}
while (1)
{
result = readLine(f, fileLen);
if (result == NULL)
break;
else
{
*(array + idx) = malloc(LENGTH * sizeof(char *));
strncpy(array[idx], result, strlen(result) + 1);
idx++;
array = realloc(array, (idx + 1) * sizeof(char *));
}
}
return array;
}
In main I created a temporary file to test my functions but it didn't work properly :
int main()
{
char filename[] = "/tmp/prefXXXXXX";
int fd;
size_t len = 0;
FILE *f;
if (-1 == (fd = mkstemp(filename)))
perror("internal error: mkstemp");
if (NULL == (f = fdopen(fd, "w")))
perror("internal error: fdopen");
for (int i = 0; i < 10000; i++)
fprintf(f, "%d\n", i);
fclose(f);
char **number = readFile(filename, &len);
for (int i = 0; i < sizeof(number) / sizeof(number[0]); i++)
printf("number[%i] = %s\n", i, number[i]);
return 0;
}
When I execute the program, I get the following output:
number[0] = 0
What am I doing wrong here ?
There are lots of issues in that code, it's difficult to find where to start...
Let's look at each function.
char *readLine(FILE *f, size_t *len)
{
char *line = NULL;
ssize_t nread;
if (f == NULL)
{
return NULL;
}
if ((nread = getline(&line, len, f)) != -1)
{
if (line[nread - 1] == '\n')
{
line[strlen(line)-1] = '\0';
*len = strlen(line);
}
return line;
}
else
{
return NULL;
}
}
There is not much wrong here. But manpage for geline tells us:
If *lineptr is set to NULL before the call, then getline() will
allocate a buffer for storing the line. This buffer should be
freed by the user program even if getline() failed.
You do not free the buffer if nread==-1 but only do return NULL; possibly causing a memory leak.
You should also check whether len==NUL as you already do it with f.
Then look at the next function:
char **readFile(const char *filename, size_t *fileLen)
{
char *result;
int idx = 0;
char **array = calloc(1, sizeof(char*) );
if (filename == NULL || fileLen == NULL)
{
return NULL;
}
FILE *f = fopen(filename, "r");
if (f == NULL)
{
return NULL;
}
while (1)
{
result = readLine(f, fileLen);
if (result == NULL)
break;
else
{
*(array + idx) = malloc(LENGTH * sizeof(char *));
strncpy(array[idx], result, strlen(result) + 1);
idx++;
array = realloc(array, (idx + 1) * sizeof(char *));
}
}
return array;
}
In this function you fail to free(array) in case you hit a return NULL; exit.
readLine puts strlen(result) into filelen. Why don't you use it to allocate memory? Instead you take some unknown fixed length LENGTH that may or may not be sufficient to hold the string. Instead you should use fileLen+1 or strlen(result)+1 as you do it with strncpy.
You are also using size of wrong type. You allocate a pointer to char, not char*. As size of char is defined to be 1 you can just drop the size part here.
Then, the length parameter for strncpy should hold the length of the destination, not the source. Otherwise it is completely useless to use strncpy at all.
As you already (should) use the string length to allocate the memory, just use strncpy.
Then, just passing fileLen to the next function does not make sense. In readLine it means length of a line while in readFile that would not make any sense. Instead it should mean number of lines. And as we just came to the topic... You should pass some value to the caller.
Finally, you should not assign the return value of realloc directly to the varirable you passed into it. In case of an error, NULL is returned and you cannot access or free the old pointer any longer.
This block should look like this:
{
array[idx] = malloc(fileLen+1);
strcpy(array[idx], result);
idx++;
void *temp = realloc(array, (idx + 1) * sizeof(char *));
if (temp != NULL)
array = temp;
// TODO: else <error handling>
}
}
*fileLen = idx;
return array;
}
This still has the flaw that you have allocated memory for one more pointer that you do not use. You can change this as further optimization.
Lastly the main function:
int main()
{
char filename[] = "/tmp/prefXXXXXX";
int fd;
size_t len = 0;
FILE *f;
if (-1 == (fd = mkstemp(filename)))
perror("internal error: mkstemp");
if (NULL == (f = fdopen(fd, "w")))
perror("internal error: fdopen");
for (int i = 0; i < 10000; i++)
fprintf(f, "%d\n", i);
fclose(f);
char **number = readFile(filename, &len);
for (int i = 0; i < sizeof(number) / sizeof(number[0]); i++)
printf("number[%i] = %s\n", i, number[i]);
return 0;
}
char **number = readFile(filename, &len); You get an array holding all the lines of a file. number is a very poor name for this.
You return NULL from readFile in case of an error. You should check for that after calling.
Then you forgot that arrays are not pointers and pointers are not arrays. They behave similar in many places but are very different at the same time.
i < sizeof(number) / sizeof(number[0])
Here number is a pointer and its size of the size of a pointer. Also number[0] is a pointer again. Different type, but same size.
What you want is the number of lines which you get from readFile. Use that variable.
This part should look like this:
char **all_lines = readFile(filename, &len);
if (all_lines != NULL)
{
for (int i = 0; i < len; i++)
printf("all_lines[%i] = %s\n", i, all_lines[i]);
And you should not forget that you have allocated a lot of memory which you should also free.
(This might not strictly be necessary when you terminate your program, but you should keep in mind to clean up behind you)
if (all_lines != NULL)
{
for (int i = 0; i < len; i++)
printf("all_lines[%i] = %s\n", i, all_lines[i]);
for (int i = 0; i < len; i++)
free(all_lines[i];
free(all_lines);
}
So I got this file and i want to scanf() only the digits inside the first {} than the digits inside the second {} and so on.
I've managed to call just the digits from the file, but I don't know how to separate them into groups
this is the file:
{5, 2, 3}, {1,5}, { }, { }, {3}, { }, { }
Below is the code I use so far
void main()
{
int rc=0,num,size;
FILE* f = fopen("graph-file.txt","rt");
if (f == NULL)
{
printf("Failed to open the file\n");
}
size = fscanf(f,"%d",&num);
fseek(f,1,SEEK_CUR);
while(rc != EOF)
{
if( rc == 1)
{
printf("%d\n",num);
}
fseek(f,1,SEEK_CUR);
rc = fscanf(f,"%d",&num);
}
}
Your code as it is has some issues, for example the mode string is wrong "rt"? You only need to specify "b" for binary and that only affects the end of line character which can be a problem if the file is read/written on different platforms.
To achieve what you want there is no simple way, as #JonathanLeffler suggests in this comment you could use a json library json-c1 is a very easy to use one.
If you want to do it yourself, try this code that I did just write
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int
append_number(int size, int **arrays, int value)
{
void *pointer;
pointer = realloc(arrays[0], (++size + 1) * sizeof(**arrays));
if (pointer == NULL)
return 0;
arrays[0] = pointer;
arrays[0][size] = value;
return 1;
}
int
get_value(const char *input)
{
if (input == NULL)
return -1;
while ((*input != '\0') && (isspace((unsigned char) *input) != 0))
input++;
if (*input == '\0')
return -1;
return atoi(input);
}
int *
extract_arrays(char *array)
{
int value;
int *list;
list = malloc(sizeof(*list));
if (list == NULL)
return NULL;
list[0] = 0;
while (array != NULL)
{
char *delimiter;
delimiter = strchr(array, ',');
if (delimiter != NULL)
*delimiter = '\0';
value = get_value(array);
if (value > 0)
list[0] += append_number(list[0], &list, value);
if (delimiter != NULL)
array = delimiter + 1;
else
array = NULL;
}
return list;
}
void
print_array(int *list)
{
fprintf(stdout, "[");
for (int j = 1 ; j < list[0] ; ++j)
fprintf(stdout, "%d ", list[j]);
if (list[0] > 0)
fprintf(stdout, "%d", list[list[0]]);
fprintf(stdout, "]\n");
}
int **
parse_line(char *line, size_t *count)
{
char *open;
char *close;
char *next;
int **arrays; // Depends on the maximum size of an inner array
*count = 0;
arrays = NULL;
next = line;
while ((next != NULL) && ((open = strchr(next, '{')) != NULL))
{
close = strchr(open, '}');
if (close != NULL)
{
void *pointer;
char *values;
*close = '\0';
next = strchr(close + 1, ',');
values = open + 1;
pointer = realloc(arrays, (*count + 1) * sizeof(*arrays));
if (pointer == NULL)
goto error;
arrays = pointer;
arrays[(*count)++] = extract_arrays(values);
}
else
next = open + 1;
}
return arrays;
error:
for (size_t i = 0 ; i < *count ; ++i)
free(arrays[i]);
free(arrays);
*count = 0;
return NULL;
}
int main(void)
{
char line[100];
size_t count;
int **arrays;
FILE *file;
file = fopen("graph-file.txt", "r");
if (file == NULL)
return -1; // Failure openning the file
while (fgets(line, sizeof(line), file) != NULL)
{
arrays = parse_line(line, &count);
for (size_t i = 0 ; i < count ; ++i)
{
print_array(arrays[i]);
// DO something with it ...
free(arrays[i]);
}
free(arrays);
}
fclose(file);
return 0;
}
Of course, there are a lot of possible optimizations (specially the realloc() parts), but I leave that to you.
Above, the int ** pointer returned by parse_line() contains count arrays where the first element is the length of each array.
1I know that on most linux distributions it can be installed with the package manager, and I have been using it a lot recently for some web development related projects.
Arrays are probably what you're going to need to accomplish this task. Arrays allow you to have various amounts of digits that you can store what you read into. That's how you can separate the groupings. The next part will be how to change which part of the array you're looking at, which this link should also help with.
C Arrays Tutorial.
If the numbers that you're trying to read will only be single digit numbers, then you could ditch the fseek and fscanf functions and use getc instead. Just check each read for anything that's not a number '0'-'9'.
C getc
Those websites I linked also have a lot of other good tutorials on them for learning C\C++.
Good luck.
Edit: less condescending.
this is an assignment for my CS course,
im trying to write a code that reads a file line by line and put the input into a struct element.the struct looks like this:
typedef char* Name;
struct Room
{
int fStatus;
Name fGuest;
};
the status is 0 for available and 1 for booked. the name will be empty if the room is available.
there are 2 function, one to read and put the values to a struct element, and the other one to print it out.
int openRoomFile()
{
FILE *roomFile;
char *buffer = NULL;
size_t length = 0;
size_t count = 0;
roomFile = fopen("roomstatus.txt", "r+");
if (roomFile == NULL)
return 1;
while (getline(&buffer, &length, roomFile) != -1) {
if (count % 2 == 0) {
sscanf(buffer, "%d", &AllRooms[count].fStatus);
} else {
AllRooms[count].fGuest = buffer;
}
count++;
}
fclose(roomFile);
free(buffer);
return 0;
}
print function
void printLayout(const struct Room rooms[])
{
for (int i=0; i<3; i++) {
printf("%3d \t", rooms[i].fStatus);
puts(rooms[i].fGuest);
}
}
the output is not what i expected, given the input file is :
1
Johnson
0
1
Emilda
i will get the output :
1 (null)
0
0 (null)
i dont know what went wrong, am i using the right way to read the file? every code is adapted from different sources on the internet.
Here is a fixed version of the openRoomFile()
int openRoomFile(void)
{
FILE *roomFile;
char *buffer = NULL;
size_t length = 0;
size_t count = 0;
roomFile = fopen("roomstatus.txt", "r+");
if (roomFile == NULL)
return 1;
while (1) {
buffer = NULL;
if (getline(&buffer, &length, roomFile) == -1) {
break;
}
sscanf(buffer, "%d", &AllRooms[count].fStatus);
free(buffer);
buffer = NULL;
if (getline(&buffer, &length, roomFile) == -1) {
fprintf(stderr, "syntax error\n");
return 1;
}
AllRooms[count].fGuest = buffer;
count++;
}
fclose(roomFile);
return 0;
}
When you no longer need those fGuest anymore, you should call free on them.
If your input is guaranteed to be valid (as were many of my inputs in my CS classes), I'd use something like this for reading in the file.
while(!feof(ifp)){
fscanf(ifp,"%d%s",&AllRooms[i].fStatus, AllRooms[i].fGuest); //syntax might not be right here
//might need to play with the '&'s
//and maybe make the dots into
//arrows
//do work here
i++;
}
You are not allocating memory for Name. Check this. In the below example i'm not included free() calls to allocated memory. you need to call free from each pointer in AllRooms array, once you feel you are done with those and no more required.
#include<stdio.h>
#include<stdlib.h>
typedef char* Name;
struct Room
{
int fStatus;
Name fGuest;
}Room_t;
struct Room AllRooms[10];
int openRoomFile()
{
FILE *roomFile;
char *buffer = NULL;
size_t length = 0;
size_t count = 0;
size_t itemCount = 0;
roomFile = fopen("roomstatus.txt", "r+");
if (roomFile == NULL)
return 1;
buffer = (char *) malloc(16); // considering name size as 16 bytes
while (getline(&buffer, &length, roomFile) != -1) {
if (count % 2 == 0) {
sscanf(buffer, "%d", &AllRooms[itemCount].fStatus);
} else {
AllRooms[itemCount].fGuest = buffer;
itemCount++;
}
count++;
buffer = (char *) malloc(16); // considering name size as 16 bytes
}
fclose(roomFile);
free(buffer);
return 0;
}
void printLayout(const struct Room rooms[])
{
int i;
for (i=0; i<3; i++) {
printf("%3d \t", rooms[i].fStatus);
puts(rooms[i].fGuest);
}
}
int main(void)
{
openRoomFile();
printLayout(AllRooms);
// free all memory allocated using malloc()
return 0;
}
After a long time I'm playing with dynamic memory allocation in C and I'm encountering some issues with memory leaks ... I just can't see where the problem might be. Can Anyone help please?
EDIT2:
The program now works fine even with very large numbers and is quite quick :) I decided to change the program structure and used struct instead of just char string. There should not be any memory leaks (tested with valgrind).
Current code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct binary{
char * number;
size_t length;
}Tbinary;
//exterminate leading zeros
size_t exterminate(char * bin, size_t length){
char * pch = NULL;
long position = 0;
pch = strchr(bin, '1');
if(pch==NULL){
bin[1] = '\0';
length = 2;
}
else{
position = pch-bin;
strcpy(bin, pch);
}
return (length-position);
}
int binaryAdd(Tbinary first, Tbinary second){
int a=0, b=0, sum=0, carry=0;
size_t index = first.length;
first.number[first.length] = '\0';
while((first.length != 0) || (carry != 0)){
if(first.length>1) a= first.number[first.length-2]-'0';
else a = 0;
if(second.length>1) b= second.number[second.length-2]-'0';
else b = 0;
sum = (a+b+carry)%2;
first.number[first.length-1] = (sum)+'0';
carry = (a+b+carry)/2;
if(first.length >0)first.length--;
if(second.length >0)second.length--;
}
exterminate(first.number,index);
printf("Sum: %s\n", first.number);
return EXIT_SUCCESS;
}
int get_number(Tbinary *bin_addr){
char * tmp, * bin;
char ch=1;
int size = 1, index = 0;
bin = bin_addr->number;
while(ch){
ch = getc(stdin);
if((ch == '\n') || (ch == ' ')) ch = '\0';
if((ch-'0' != 0) && (ch-'0' != 1) && (ch != '\0')) return EXIT_FAILURE;
if (size-1 <=index){
size += 5;
tmp = (char *)realloc(bin, size*sizeof(char));
if(tmp == NULL){
return EXIT_FAILURE;
}
bin = tmp;
bin_addr->number = bin;
}
bin[index++] = ch;
}
bin_addr->length = index;
bin_addr->length = exterminate(bin_addr->number, bin_addr->length);
return EXIT_SUCCESS;
}
int main (void)
{
Tbinary bin1 = {bin1.number = NULL, bin1.length = 0};
Tbinary bin2 = {bin2.number = NULL, bin2.length = 0};
//allocate space for first number
bin1.number = (char *)malloc(sizeof(char));
if(bin1.number == NULL)
return EXIT_FAILURE;
//allocate space for second number
bin2.number = (char *)malloc(sizeof(char));
if(bin2.number == NULL){
free(bin1.number);
return EXIT_FAILURE;
}
printf("Enter two binary numbers:\n");
//number1 load
if(get_number(&bin1) != EXIT_SUCCESS){
free(bin1.number);
free(bin2.number);
printf("Invalid input.\n");
return EXIT_FAILURE;
}
//number2 load
if(get_number(&bin2) != EXIT_SUCCESS){
free(bin1.number);
free(bin2.number);
printf("Invalid input.\n");
return EXIT_FAILURE;
}
//add the two numbers
if(bin1.length >= bin2.length){
if(binaryAdd(bin1, bin2) != EXIT_SUCCESS){
free(bin1.number);
free(bin2.number);
printf("Invalid input.\n");
return EXIT_FAILURE;
}
}
else{
if(binaryAdd(bin2, bin1) != EXIT_SUCCESS){
free(bin1.number);
free(bin2.number);
printf("Invalid input.\n");
return EXIT_FAILURE;
}
}
free(bin1.number);
free(bin2.number);
return EXIT_SUCCESS;
}
In binaryAdd() you should free sum after realloc() in all cases, not just when realloc() returns null. Same thing in get_number().
About a = (int)strlen(first); why cast the return of strlen() into an int?
Also, don't cast the return of allocation functions.
You have an off-by-one error in your size and index relationship:
if (size <=index){
size += 5;
tmp = (char *)realloc(sum, size*sizeof(char));
if(tmp == NULL){
free(sum); // free memory to avoid leak
return EXIT_FAILURE;
}
sum = tmp;
}
for(int i=index; i>0; i--){
sum[i] = sum[i-1];
}
sum[0] = num%2+'0';
carry = num/2;
index++;
}
sum[index] = '\0';
If, on entering the last iteration, index == size-1, you are writing outside the allocated memory. Sometimes that can be harmless, for others you may overwrite some important data without causing an immediate crash, and sometimes it can cause an immediate crash (when the out-of-bounds access crosses a page boundary, usually). Change the test to size - 1 <= index.
In get_number, if you need to realloc, you only change the local copy of the char* to the input buffer, so if the location changes, the pointer in main points to invalid memory. It should be
int get_number(char **bin_addr){
char * tmp, bin = *bin_addr;
char ch=1;
size_t size = 1, index = 0;
while(ch){
ch = getc(stdin);
if((ch == '\n') || (ch == ' ')){
ch = '\0';
}
if((ch-'0' != 0) && (ch-'0' != 1) && (ch != '\0')){
return EXIT_FAILURE;
}
if (size-1 <=index){
size += 5;
tmp = (char *)realloc(bin, size*sizeof(char));
if(tmp == NULL){
return EXIT_FAILURE;
}
bin = tmp;
*bin_addr = bin; // let the pointer always point to the real block
}
bin[index++] = ch;
}
return EXIT_SUCCESS;
}
and be called get_number(&bin1); in main.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Doing a homework and I'm having problems with, what I believe, pointers.
The assignment consists in the following:
I have a txt file where each line as a name and a password.
thisismyname:thisismypassword
I have to read this data, process it into struct linked list, run all the list and send the password to a brute-force algorithm. This algorithm, after finding the pass, should write the pass on the struct. In the end, I should run the list and write the data to a txt file
My problem is when I find the password. It is not storing its value in the struct. At the end I can read the data, I can see that the brute-force is working but at the end, I'm only managing to write the name and pass to file. The unencrypted pass is being written as NULL so I believe is a pointer problem.
This is the code (Removed all the things that I believe are irrelevant):
typedef struct p {
char *name;
char *pass;
char *pass_desenc;
struct p *next_person;
} person;
typedef struct n {
int a;
int b;
} numbers;
int readFile(person **people) {
FILE * fp;
char line[100];
if ((fp = fopen(STUDENTS_FILE, "r")) != NULL) {
while (fgets(line, sizeof (line), fp) != NULL) {
person *p;
char email[27] = "";
char password[14] = "";
char *change = strchr(line, '\n');
if (change != NULL)
*change = '\0';
/* Gets email*/
strncpy(email, line, 26);
email[27] = '\0';
/* Gets pass*/
strncpy(password, line + 27, 14);
password[14] = '\0';
p = (person*) malloc(sizeof (person));
if (p == NULL) {
return -1;
}
p->name = (char*) malloc(strlen(email));
if (p->name == NULL) {
return -1;
}
sprintf(p->name, "%s", email);
p->name[strlen(email)] = '\0';
p->pass = (char*) malloc(strlen(password));
if (p->pass == NULL) {
return -1;
}
sprintf(p->pass, "%s", password);
p->pass[strlen(password)] = '\0';
p->next_person = (*people);
(*people) = p;
countPeople++;
}
fclose(fp);
return 0;
}
return -1;
}
void fmaps(int id, numbers pass_range, person *people) {
/*This function will run all my list and try to uncrypt pass by pass.
On the brute-force pass in unencrypted and when it return to this function, I can print the data.
*/
while (people != NULL && j > 0) {
for (i = 1; i <= PASS_SIZE && notFound == 1; i++) {
notFound = bruteForce(i, people, &total_pass);
}
notFound = 1;
count = count + total_pass;
printf("#####Email: %s Pass: %s PassDesenq: %s \n", people->name, people->pass, people->pass_desenc);
people = people->next_person;
j--;
}
}
void fcontrol(int n, person *people) {
/*This function should write the data to a file
I can see that all data is written as expected but people->pass_desenc is writing/printing NULL
*/
if ((fp = fopen(STUDENTS_LOG_FILE, "a+")) != NULL) {
while (people != NULL) {
printf("#####1111Email: %s Pass: %s PassDesenq: %s \n", people->name, people->pass, people->pass_desenc);
fprintf(fp, "%d%d%d%d%d%d:grupo%d:%s:%s\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, 1, people->name, people->pass_desenc);
people = people->next_person;
}
}
fclose(fp);
}
int main() {
/*Struct*/
person *people = NULL;
if (readFile(&people)) {
printf("Error reading file!\n");
return 0;
}
/*Function to send data to brute-force*/
fmaps(i, pass_range, people);
/*After all data is processed, this function writes the data to a file*/
fcontrol(NR_PROC, people);
destroyList(&people);
return 0;
}
int bruteForce(int size, person *people, int *total_pass) {
int i;
char *pass_enc;
int *entry = (int*) malloc(sizeof (size));
char pass[50];
char temp;
pass[0] = '\0';
for (i = 0; i < size; i++) {
entry[i] = 0;
}
do {
for (i = 0; i < size; i++) {
temp = (char) (letters[entry[i]]);
append(pass, temp);
}
(*total_pass)++;
/*Compare pass with test*/
pass_enc = crypt(pass, salt);
if (strcmp(pass_enc, people->pass) == 0) {
people->pass_desenc = (char*) malloc(strlen(pass));
if (people->pass_desenc == NULL) {
return -1;
}
sprintf(people->pass_desenc, "%s", pass);
people->pass_desenc[strlen(pass)] = '\0';
return 0;
}
pass[0] = '\0';
for (i = 0; i < size && ++entry[i] == nbletters; i++) {
entry[i] = 0;
}
} while (i < size);
free(entry);
return 1;
}
void append(char *s, char c) {
int len = strlen(s);
s[len] = c;
s[len + 1] = '\0';
}
void destroyList(person **people) {
person *aux;
printf("\nList is being destroyed.");
while (*people != NULL) {
aux = *people;
*people = (*people)->next_person;
free(aux);
printf(".");
}
printf("\nList destroyed.\n");
}
I believe that the changes being made in fmaps are local and are not passing to main.
Any help is appreciated...
This is how you could code the file reader/parser. It avoids str[n]cpy(), and does all string operations using memcpy() + the offsets + sizes. (which need to be correct in both cases, obviously)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
typedef struct p {
char *name;
char *pass;
// char *pass_desenc;
struct p *next;
} person;
#define STUDENTS_FILE "students.dat"
unsigned countPeople = 0;
int readFile(person **people) {
FILE * fp;
char line[100];
size_t len, pos;
fp = fopen(STUDENTS_FILE, "r");
if (!fp) {
fprintf(stderr, "Could not open %s:%s\n"
, STUDENTS_FILE, strerror(errno));
return -1;
}
while ( fgets(line, sizeof line, fp) ) {
person *p;
len = strlen(line);
/* remove trailng '\n', adjusting the length */
while (len && line[len-1] == '\n') line[--len] = 0;
/* Ignore empty lines */
if ( !len ) continue;
/* Library function to count the number of characters in the first argument
** *not* present in the second argument.
** This is more or less equivalent to strtok(), but
** 1) it doen not modify the string,
** 2) it returns a size_t instead of a pointer.
*/
pos = strcspn(line, ":" );
/* Ignore lines that don't have a colon */
if (line[pos] != ':') continue;
p = malloc(sizeof *p);
if ( !p ) { fclose(fp); return -2; }
p->next = NULL;
p->name = malloc(1+pos);
if ( !p->name ) { fclose(fp); return -3; } /* this could leak p ... */
memcpy(p->name, line, pos-1);
p->name[pos] = 0;
p->pass = malloc(len-pos);
if ( !p->pass ) {fclose(fp); return -4; } /* this could leak p and p->name */
memcpy(p->pass, line+pos+1, len-pos);
/* Instead of pushing (which would reverse the order of the LL)
** , we append at the tail of the LL, keeping the original order.
*/
*people = p;
people = &p->next ;
countPeople++;
}
fclose(fp);
return 0;
}