| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | malloc and the resulting |
DC> I got a problem with malloc();
I'll say!!
Have a look at this once:
/*_|_| IREADME.C PUBLIC DOMAIN Kurt Kuzba 10/23/1998
_|_|_| A simple example of using malloc() with a line buffer
_|_|_| to read and rewrite a text file. */
#include
#include
#define MAX 50
int main(void)
{
FILE *Me, *Test; /* one for read file, one write */
char *Linebuf[MAX] = {NULL};/* an array of char pointers */
int iterator; /* an int to count iterations */
for(iterator = 0; iterator < MAX; iterator++)
{ /* malloc buffer for each char* */
Linebuf[iterator] = malloc(128 * sizeof(char));
if(NULL == Linebuf[iterator])
{ /* on error, free all allocated */
while((--iterator) > -1)
free(Linebuf[iterator]);
puts("\nMalloc error.");
return 1;
}
}
Me = fopen("ireadme.c", "rb");
if(!Me) /* open read file, test error */
{
puts("Unable to open \"ireadme.c\".");
}
else
{
Test = fopen("testme.txt", "wb");
if(NULL == Test) /* open write file, test error */
{
puts("Unable to open \"testme.txt\".");
}
else
{ /* read lines, display, write */
for(iterator = 0; iterator < MAX; iterator++)
fgets(Linebuf[iterator], 128, Me);
for(iterator = 0; iterator < MAX; iterator++)
printf(Linebuf[iterator]);
for(iterator = 0; iterator < MAX; iterator++)
fprintf(Test, Linebuf[iterator]);
fclose(Test); /* close write file */
}
fclose(Me); /* close read file */
}
for(iterator = 0; iterator < MAX; iterator++)
free(Linebuf[iterator]); /* delete each block allocated */
return 0;
}
> ] * Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)SEEN-BY: 396/1 632/0 371 633/260 267 270 371 634/397 635/506 728 810 639/252 SEEN-BY: 670/218 @PATH: 154/750 222 396/1 633/260 635/506 728 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.