I wrote a program that tries to store the whole content of a file (its own source code) in a pointer to char variable, and then tries to print that content when the EOF is reached in the file. The program is crashing so far. I added the following line to it, so that I can clearly see the character just read:
printf( "***%c***\n", currentCharacter );
The program compiles and links properly, but the output ends up being:
The program is:
Code:
#include <stdio.h>
#include <stdlib.h>
int stringLength( char *arr );
int main( void )
{
int counter = 0;
char *charPtr = NULL;
char currentCharacter;
FILE *filePtr = fopen( "read_content_to_array.c", "r" );
if ( filePtr != NULL )
{
while ( !feof( filePtr ) )
{
currentCharacter = fgetc( filePtr );
printf( "***%c***\n", currentCharacter );
if ( counter > 0 )
{
if ( ( charPtr = realloc( charPtr, ( 1 + stringLength( charPtr ) ) * sizeof( char ) ) ) != NULL )
{
*( charPtr + counter ) = currentCharacter;
*( charPtr + counter + 1 ) = '\0';
}
else
{
printf( "Memory error...\n" );
return 1;
}
}
else
{
if ( ( charPtr = malloc( 2 * sizeof( char ) ) ) != NULL )
{
*( charPtr + counter ) = currentCharacter;
*( charPtr + counter + 1 ) = '\0';
}
else
{
printf( "Memory error...\n" );
return 1;
}
}
++counter;
}
if ( counter > 0 )
{
printf( "%s", charPtr );
free( charPtr );
}
fclose( filePtr );
}
else
{
printf( "File error...\n" );
return 1;
}
return 0;
}
int stringLength( char *arr )
{
int i = 0;
int length = 0;
while ( *( arr + i++ ) != '\0' )
{
++length;
}
return length;
}
What am I doing wrong? Thanks in advance.
[EDIT:] I tried using two pointer variables, as suggested to telmo_d in the last answer of the topic located in How to get address of the start of the memory allocated?, but the program still crashes. Here's the modified program:
Code:
#include <stdio.h>
#include <stdlib.h>
int stringLength( char *arr );
int main( void )
{
int counter = 0;
char *charPtr1;
char *charPtr2;
char currentCharacter;
FILE *filePtr = fopen( "read_content_to_array.c", "r" );
if ( filePtr != NULL )
{
while ( !feof( filePtr ) )
{
currentCharacter = fgetc( filePtr );
printf( "***%c***\n", currentCharacter );
if ( counter > 0 )
{
if ( ( charPtr2 = realloc( charPtr1, ( 1 + stringLength( charPtr1 ) ) * sizeof( char ) ) ) != NULL )
{
charPtr1 = charPtr2;
*( charPtr1 + counter ) = currentCharacter;
*( charPtr1 + counter + 1 ) = '\0';
}
else
{
printf( "Memory error...\n" );
return 1;
}
}
else
{
if ( ( charPtr1 = malloc( 2 * sizeof( char ) ) ) != NULL )
{
*( charPtr1 + counter ) = currentCharacter;
*( charPtr1 + counter + 1 ) = '\0';
}
else
{
printf( "Memory error...\n" );
return 1;
}
}
++counter;
}
if ( counter > 0 )
{
printf( "%s", charPtr1 );
free( charPtr1 );
free( charPtr2 );
}
fclose( filePtr );
}
else
{
printf( "File error...\n" );
return 1;
}
return 0;
}
int stringLength( char *arr )
{
int i = 0;
int length = 0;
while ( *( arr + i++ ) != '\0' )
{
++length;
}
return length;
}