1

I'm executing a program from command line, it takes string integer string string parameters, I call a function that reads the following file:

sólo te lo diré mañana al mediodía en la biblioteca

It reads the file and prints what it is supposed to print but when it goes back to the main function the value NumHijos takes a random value, why does it happen? I am not even using it in any function

Main program, let's say we have this command line ./program -d 4 File1 File2

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include "file.h"


int main(int argc, char *argv[]) {
    /*command line args*/
    int NumHijos;
    int op = 0;

    size_t len = strlen(argv[1]);
    char * operacion = malloc(len+2);
    strcpy(operacion, argv[1]);

    NumHijos = atoi(argv[2]);

    len = strlen(argv[3]);
    char * file1 = malloc(len+5);
    strcpy(file1, argv[3]);
    strcat(file1,".txt");

    len = strlen(argv[4]);
    char * file2 = malloc(len+5);
    strcpy(file2, argv[4]);   

    char vector [NumHijos];

    printf("Arg 1: %s\n",operacion); 
    printf("Arg 2: %d\n",NumHijos); 
    printf("Arg 3: %s\n", file1);
    printf("Arg 4: %s\n\n", file2); 

    abrirArchivoEntrada(file1, vector, NumHijos);

    int i = 1;

    if (operacion[1] == 'd'){
        printf("decypher\n");
    }

    else if (operacion[1] == 'c'){
        printf("crypt\n");
    }
    return 0; 
    printf("times %d", NumHijos);

}

file.h

void llenarVector(FILE *e, char texto [], int n) {
    int l;
    while (!feof(e)){
        fgets(texto, 1000, e);
    }

    l = strlen(texto);
    printf("%s\n", texto);
    printf("%d\n", l);

 fclose(e);
}

void abrirArchivoEntrada (char * nombre, char texto[], int n){
    FILE *e;
    e = fopen(nombre, "r");
            if (e == NULL) 

            {
                printf("error\n");
            }
            else { 
                printf("loaded successfully\n");    
                llenarVector(e,texto,n);
            }
}
FlowMafia
  • 922
  • 2
  • 19
  • 37
  • Most likely stack corruption. Try running your program under valgrind or similar tool. One potential problem is that `llenarVector` assumes `texto` has room for 1000 characters, but you pass in `vector` which doesn't necessarily have room for that many characters. – user786653 May 31 '19 at 21:06
  • 3
    `malloc(len+3);` Well, `.txt` is 4, the nul terminator is 1, so you need more than +3 don't you think? – Retired Ninja May 31 '19 at 21:07
  • 1
    You shouldn't define functions in header files. – melpomene May 31 '19 at 21:07
  • Think about how many additional bytes you need to store ".txt" and a null-terminator. Is it 3? – jarmod May 31 '19 at 21:07
  • @user786653 i don't know how many characters the var "texto" could have, is there any way I can reprogram this so I don't have to put that 1000? – FlowMafia May 31 '19 at 21:07
  • @FlowMafia did you apply what is suggested in the second comment? Did it help? Don't ask another question in a comment. – Jabberwocky May 31 '19 at 21:14
  • @Jabberwocky yes, I have the same issue – FlowMafia May 31 '19 at 21:21
  • The buffer length isn't `1000` but the value you entered for `NumHijos = atoi(argv[2]);` which should be passed to the function. – Weather Vane May 31 '19 at 21:22
  • @WeatherVane Oh, it isn't exactly that but you made me realize why it's happening, I made the array's length of the size that is passed through the command line, and I wasn't supposed to do that, so when I called the function it was writing in the array out of boundaries, i changed char vector[NumHijos] for char vector [1000] and it worked, so thank you :) – FlowMafia May 31 '19 at 21:26

1 Answers1

3
len = strlen(argv[3]);
char * file1 = malloc(len+3);
strcpy(file1, argv[3]);
strcat(file1,".txt");

Is undefined behavior. ".txt" needs 4 more characters, so you need to allocate strlen(argv[3]) + 5 bytes for file1 pointer.

while (!feof(e)) is always wrong.

fgets(texto, 1000, e); (most probably) is way into undefined behavior. The texto pointer points to char vector[NumHijos];. The variable is initialized with NumHijos = atoi(argv[2]);, where argv[2] is passed 2. So vector is a variable length array with only 2 bytes. Yet you try to write 1000 bytes into the vector with fgets call - this most probably accesses the pointer out of bounds and undefined behavior happens.

Once undefined behavior happens, you can't have any expectations as to what the program will produce. Probably the fgets function overwrites the memory behind NumHijos variable. Or strcat overwrites it. Debug the program to find out. How to debug small programs.

i don't know how many characters the var "texto" could have, is there any way I can reprogram this so I don't have to put that 1000?

Yes. Use getline if you have it, if not rewrite it on your own. Writing a function that reads a file char by char, reallocates some destination pointer and stores read character into that pointer looks like a good C training. Anyway, here's the libcs50 library with it's get_string() function which may serve as a good reference how to implement such function.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111