By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,820 Members | 1,187 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,820 IT Pros & Developers. It's quick & easy.

Do you see a problem?

P: n/a
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;

}

Jun 13 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
dk*******@gmail.com wrote:
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.

--
Ian Collins.
Jun 13 '06 #2

P: n/a
dk*******@gmail.com wrote:
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 <> around the name, not "".
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;

}


Jun 13 '06 #3

P: n/a
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];"
dk*******@gmail.com wrote:
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;

}


Jun 14 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.