Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length

 
Advanced search

1075927 Posts in 44152 Topics- by 36120 Members - Latest Member: Royalhandstudios

December 29, 2014, 03:57:28 PM
TIGSource ForumsDeveloperTechnical (Moderators: Glaiel-Gamer, ThemsAllTook)Memory allocation
Pages: [1]
Print
Author Topic: Memory allocation  (Read 543 times)
Carlos_PRO
Guest
« on: July 06, 2012, 01:56:13 PM »

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
Code:
#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
Code:
#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
Logged
Nix
Level 10
*****



View Profile
« Reply #1 on: July 06, 2012, 02:18:20 PM »

You have misunderstood sizeof and malloc. You didn't include all your code so I can't help much more than that, but you need to go back and read up more on how sizeof and malloc work.
Logged
ThemsAllTook
Moderator
Level 10
******


Alex Diener


View Profile WWW
« Reply #2 on: July 06, 2012, 02:24:00 PM »

Wow, so many problems I don't know where to start!

  • sizeof doesn't work that way. It's a compile-time constant that gives you the number of bytes of the type you use it in. You're using it on a FILE *, so that'll give you the size of a pointer, which is likely to be either 4 or 8 bytes depending on your CPU architecture. To get the length of a file, you can either use stat (or fstat), or fseek to the end of the file and use ftell.
  • You're calling malloc when assigning size, and passing the result to another malloc call later. What that's going to do is try to allocate a number of bytes equal to the pointer address the first malloc returns you. Not useful and not likely to even succeed in the allocation.
  • You're casting the result of a malloc call to char. This means you're truncating the returned address to a single byte. Even if you weren't calling malloc and were just taking the file's actual size, your code would only work with a maximum file length of 127 bytes if you cast it to char.
  • You're calculating size twice for no good reason.
  • Using an else when the main branch of an if calls exit muddies up your control flow. No need for the else, since it's impossible for the code in it to be executed without the rest of the function proceeding.

There may be other problems in here too, but these are the ones that pop out at me immediately.
Logged
Carlos_PRO
Guest
« Reply #3 on: July 06, 2012, 04:53:56 PM »

thanks, i look the ftell function and she works the way I wanted, too change the type of size for int because of limit of characters that the char type accept and now the code was as follows. I'm still studying memory allocation so my lack of practice with some things. The code was now as follows:
Code:
#include "main.h"

void file_open(void)
{
if(!(fp_read = fopen("link_entrada.txt", "r")))
{
fprintf(stderr, "Error to open read file.");
exit(ERROR);
}

if(!(fp_write = fopen("link_saida.txt", "w")))
{
fprintf(stderr, "Error to open write file");
exit(ERROR);
}

return;
}

void file_read(char *link_to_read)
{
fread(link_to_read, sizeof(char), size, fp_read);

return;
}

void file_write(char *link_to_write)
{
fwrite(link_to_write, sizeof(char), size, fp_write);

return;
}

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; i >= 0; --i, j++)
{
new_link[j] = link_to_reverse[i];
}

return(new_link);
}

void file_close(void)
{
fclose(fp_read);
fclose(fp_write);

return;
}

int main(int argc, char *arg[])
{
char *link    = NULL;
char *reverse_link = NULL;

/* open the files*/
file_open();

/* Set the file size */
fseek(fp_read, 0, SEEK_END);
size = ftell(fp_read);
fseek(fp_read, 0, SEEK_SET);

/* memory allocation for characters */
link = (char *)malloc(size);
reverse_link = (char *)malloc(size);

/* read links */
file_read(link);

/* write links in output */
file_write(link_reverse(link, reverse_link));

/* close files */
file_close();

system("pause");
return 0;
}

He is working the way I wanted, but if you find any error in the code and so to speak.
Logged
ThemsAllTook
Moderator
Level 10
******


Alex Diener


View Profile WWW
« Reply #4 on: July 06, 2012, 07:50:04 PM »

Much better, looks right to me now! If this code was anywhere other than at the end of main(), you'd want to be sure to call free() on link and reverse_link once you're done with them. As it is, though, the system will reclaim the memory when your program exits.
Logged
Carlos_PRO
Guest
« Reply #5 on: July 07, 2012, 02:20:46 PM »

Yeah, I forgot this detail, but already patched.
Logged
Sean Hogan (seagaia)
Level 10
*****


Coupons


View Profile WWW Email
« Reply #6 on: July 07, 2012, 02:31:53 PM »

Code looks good now, keep in mind that it would also be fine if you just did

link_reverse(link, reverse_link);
file_write(reverse_link);

although chaining the two functions as you did is fine.

It's likely you know this, but if not, it's important - after the call to link_reverse, reverse_link will always have a pointer to the reversed array of characters, as the changes you made to memory in link_reverse are permanent throughout the scope of reverse_link.

Basically if you wanted to do something additional with the reversed array of chars, you wouldn't have to call link_reverse again, you can just use that reverse_link pointer.
Logged

Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic