fopen does not work and SIGSEGV sends me in debug and another error in normal compilation

1

Basically I want to make a program that "divides" the routes in which the file is that I am specifying, that I already achieve, however I also want to access this file with everything and the route so I use fopen and place as variable the string with everything and the route, however at the time of reading this file sends me different errors either in debug mode or normal compilation, in debug SIGSEGV sends me and in normal compilation namas takes me out of the program.

According to the debug, the file fp when I use fopen sends null, but in the bin if I create it but sometimes with the name changed in some letters (like garbage), and finally the error lies in that, that it does not I understand why he pulls me in fopen null, I've been trying for several days to understand why it does not work and I really do not see form, I would appreciate that expert people like you could answer me, (is my first question on this site) I leave the code:

///esto es un header, que luego invoco la funcion connectToDB en el main
///pero eso no es el error sino al usar la funcion fopen
typedef struct empleado{
int ID;
char nombre[30];
char apellido[30];
char sexo;//Masculino Femenino //m, f
int antiguedad;
char estadoCivil [13];//casado soltero viudo divorciado //c,s,v,d
int hijosEstudiando;
int horasTrabajadas;
int bonoLibros;
float aumento;
float sueldo;
float valeDespensa;
}Empleado;
///en el main ya habia declarado un empleado,y ese pase de parametro mas 
 //adelante
char* getCurrentDirectory(char* fileName){
// Get the current working directory:
char* buffer;

if( (buffer = _getcwd( NULL, 0 )) == NULL )
  perror( "_getcwd error" );

else{
strcat(buffer,"\");
strcat(buffer,fileName);
printf( "%s \nLength: %d\n", buffer, strlen(buffer));
}
return buffer;
}
void resetBuffer(char* buffer){
memset(buffer,0,strlen(buffer));
 }

 int connectToDB(Empleado registro[]){
 FILE *fp;
 FILE *bfp;
 int i=0,flag=1;
 char* path;
 path=getCurrentDirectory("DataSystem Empleados.txt");
 perror( "_buffer error?");//sends invalid argument
 printf("\nBREAKPOINT\n");

 if( (fp = fopen(path,"r"))==NULL ){
  printf("file wasnt read\n");
 }
 else{
  printf("file read succesfuly\n");
 }
  resetBuffer(path);

  path=getCurrentDirectory("DataSystem Empleados.bin");
  perror( "_buffer error?");
  printf("\nBREAKPOINT\n");

  if( (bfp = fopen(path,"w+"))==NULL ){
   printf("file wasnt created\n");
   }
  else{
     printf("file created succesfully\n");
   }
    perror( "_buffer error?");
    printf("\nBREAKPOINT\n");

    fclose(bfp);
    bfp=fopen(path,"ab+");
    resetBuffer(path);

 if(fp==NULL || bfp==NULL ){//a veces hasta aqui llega el programa o entra
perror("Error: ");
printf("\n\nDB connection failed\n");
  return(-1);
 }
 else{
 flag=0;
   char auxEC[13];
  while(1){
       printf("%d\n",i+1);
       fscanf(fp,"%d %s %s %c %d %s %d %d",
       &(registro[i].ID),
       (registro[i].nombre),
       (registro[i].apellido),
       &(registro[i].sexo),
       &(registro[i].antiguedad),
       (registro[i].estadoCivil),
       &(registro[i].hijosEstudiando),
       &(registro[i].horasTrabajadas));
       /// aqui no importa solo es validacion de campos del struct 
       registro[i].sexo=validateSexo(registro[i].sexo);
       strcpy(auxEC,registro[i].estadoCivil);
       strcpy(registro[i].estadoCivil,validateEstadoCivil(auxEC));
       registro[i].sueldo=calcSueldo(registro,i);

    fwrite(registro,sizeof(Empleado),1,bfp);///escribir en binario
    i++;
      if(feof(fp)) {
         break;
      }
   }
 }
    fclose(fp);
    fclose(bfp);
if (flag ==0)
  printf("\nConexion establecida,se han leido los datos del DB...%d\n\n",i);
  return i;
}

error in debug mode error with normal compilation

    
asked by adrian cabrera 28.05.2017 в 10:34
source

1 answer

1

Let's start with this call:

if( (buffer = _getcwd( NULL, 0 )) == NULL )

According to the _getcwd documentation:

  

a buffer with a minimum size of maxlen is automatically assigned (more only if necessary) using malloc, to store the path. This buffer can be released later by calling free and passing the return value of _getcwd (a pointer to the allocated buffer).

And also:

  

The buffer function can be NULL; a buffer with a minimum size of maxlen is automatically assigned (more only if necessary) using malloc, to store the access path.

For simplicity, if the function receives a null pointer, it will make a minimum reservation necessary to store the route ... not one more byte. Well, now you do:

strcat(buffer,"\");
strcat(buffer,fileName);

What strcat does is add characters to the previous buffer, remember that is already full . strcat does not complicate life. He does not know the size of the buffer and he does not care about it ... you tell him to concatenate something and he does it ... what happens is that when leaving the memory you have assigned the Operating System detects the problem and kills the process because today's OS does not like a process to corrupt memory that does not belong to it.

What you have to do is force a larger memory reserve to avoid getting out of the buffer you have assigned.

One possible solution, to understand it better, would be to create a larger buffer for the new characters to enter:

// suponemos que el nombre del fichero no tendrá más de 98 caracteres
buffer = realloc(buffer,strlen(buffer) + 100);
if( !buffer ) // La nueva reserva puede fallar
  // ...

strcat(buffer,"\");
strcat(buffer,fileName);
    
answered by 31.05.2017 / 09:49
source