Do you see a problem?

D

dkumar142

It is a simple example. But it gives run time error regarding memory.
Do you see any error? Is it related to dynamic memory allocation?
Any help would be appreciated.
Thank you.

#include "stdio.h"
int main()
{
FILE *outFile;
char *array;
array[0]='s';
array[1]='\0';

outFile = fopen("output.txt", "w");
printf("%c \n",array[0]);
fprintf(outFile, array);

return 0;

}
 
I

Ian Collins

It is a simple example. But it gives run time error regarding memory.
Do you see any error? Is it related to dynamic memory allocation?
Any help would be appreciated.
Thank you.

#include "stdio.h"
int main()
{
FILE *outFile;
char *array;
array[0]='s';
array[1]='\0';
You don't allocate any memory for array. As this looks like C, you
should malloc (and later free) some memory for the array.
 
R

Rolf Magnus

It is a simple example. But it gives run time error regarding memory.
Do you see any error? Is it related to dynamic memory allocation?
Any help would be appreciated.
Thank you.

#include "stdio.h"

You should include system headers with said:
int main()
{
FILE *outFile;
char *array;

Ok, here you have a pointer to a char. Hover, that pointer is still
uninitialized, so it doesn't point to any valid memory yet.
array[0]='s';

Here you are attempting to write to the memory that 'array' points to. Since
it's still uninitialized, this results in undefined behavior, which is
probably the reason for your crash.
array[1]='\0';

outFile = fopen("output.txt", "w");
printf("%c \n",array[0]);
fprintf(outFile, array);

return 0;

}
 
C

crzadeh

I ran the program in Borland C++ environment, but it didn't give me any
error.
I Just had a warning in 6th line "possible use of array before
definition".
To remove this warning you can change "char *array;" to "char
array[2];"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top