I have a problem with memory allocation. My software read a string of one text document and make a inversion of this string and copy in another text document, but, i'm trying make that software do the memory allocation according with the text document size, but , he allocates memory for one text document as if he have a size predeterminate.
He's my code, if someone help me i thank.
main.c
#include "main.h"
/* Abertura dos arquivos */
void file_open(void)
{
/* Abertura do arquivo para leitura e escrita */
if(!(fp_read = fopen("link_entrada.txt", "r")))
{
fprintf(stderr, "Erro ao abrir o arquivo para leitura.");
exit(ERROR);
}
else
size = (char)malloc(sizeof(fp_read));
if(!(fp_write = fopen("link_saida.txt", "w")))
{
fprintf(stderr, "Erro ao abrir o arquivo para escrita");
exit(ERROR);
}
else
size = (char)malloc(sizeof(fp_read));
return;
}
/* Lê os links */
void file_read(char *link_to_read)
{
fread(link_to_read, sizeof(char), size, fp_read);
return;
}
/* Escreve os links no arquivo de saida */
void file_write(char *link_to_write)
{
fwrite(link_to_write, sizeof(char), size, fp_write);
return;
}
/* Inverte o link */
char *link_reverse(char *link_to_reverse, char *new_link)
{
register int i = 0;
register int j = 0;
/*int link_length = 0;
link_length = strlen(link_to_reverse);*/
for(i = size-1, j = 0; i >= 0; --i, j++)
{
new_link[j] = link_to_reverse[i];
}
return(new_link);
}
/* Fecha os arquivos abertos */
void file_close(void)
{
fclose(fp_read);
fclose(fp_write);
return;
}
int main(int argc, char *arg[])
{
char *link = NULL;
char *reverse_link = NULL;
/* Abre os arquivos */
file_open();
/* Aloca memoria para os caracteres */
link = (char *)malloc(size);
reverse_link = (char *)malloc(size);
printf("%d", size);
/* Le links do arquivo */
file_read(link);
/* Escreve os links no arquivo de saida */
file_write(link_reverse(link, reverse_link));
/* Fecha os arquivos */
file_close();
system("pause");
return 0;
}
main.h
#ifndef _MAIN_H_
#define _MAIN_H_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ERROR -1
#define MAX 255
/* Arquivos que serão usados */
FILE *fp_read = NULL;
FILE *fp_write = NULL;
char size = 0;
/* Prototipos de funções */
void file_open(void);
void file_read(char *link_to_read);
void file_close(void);
void file_write(char *link_to_write);
char *link_reverse(char *link_to_reverse, char *new_link);
#endif