Jump to content
  • Advertisement
Sign in to follow this  
Maquiavel

Problem with C streams..

This topic is 5142 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I've started studying files and streams in C today. So, I wrote a test code.. but it compiles.. and when it starts running, windows shows the message that "The window found a problem and this program must be closed"... Below is the code. What is wrong?
#include<stdio.h>

int main()
{
    FILE *fp;
    char *str;
    
    if(!(fp = fopen("arquivos/strings.txt", "w+")))
    {
        puts("Nao foi possivel abrir o arquivo...");
        getch();
        return 0;
    }
    
    str = "Programacao em C...\nAprendendo a programar em C, para partir\nà programação de jogos!\n";
    fputs(str, fp);
    
    rewind(fp); /* volta para o início do arquivo */
    
    while(!feof(fp))    
    {
        fgets(str, 50, fp);
        printf("%s", str);
    }
    
    fclose(fp);
    getch();
    return 0;    
} 




Thanks and sorry for this very nooby problem.

Share this post


Link to post
Share on other sites
Advertisement
You never allocated memory for str. Declare it like say, char str[51]; and I think you'll be fine. However, I never counted the length of your message. I think you can use strcpy to put your text in, as once you make it not a pointer, you can't set text equal to it. Windows bonks you because you're writing to non existant memory.

Share this post


Link to post
Share on other sites
just change it to

char * str[x];

except change the x to a number like 255 or however long your string will be +1 (i think?)

you dont need to assign it to anything (exclude the = "String Here"; or whatever)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Maquiavel
Thanks for your reply.
I changed char *str to char str[50] = "String Here" and the error persists.


I don't think that statement really changed anything. You declare the str variable (and 50 chars are set aside) but then assign str to a string. This basically says that the str variable (which works somewhat like a pointer), is set to a place in memory where "String Here" is located.

When the program compiles and runs, all of these explicit strings must exist somewhere in memory. The "initialization" statement above just changes the location in memory where you expect the 50 element array to exist. If you write to that array, you might overwrite other data or into memory outside your user space (hence a segmentation fault).

So to initialize your str[50] variable, use something like strcpy or memset - always being careful not to overrun the array bounds.

Share this post


Link to post
Share on other sites
Now I'm trying with>


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
FILE *fp;
char *str;

strcpy(str, "Programacao em C...\nAprendendo a programar em C, para partir à programação de jogos...");

if(!(fp = fopen("strings.txt", "w+")))
{
puts("Nao foi possivel abrir o arquivo...");
getch();
return 0;
}

fputs(str, fp);

rewind(fp);

while(!feof(fp))
{
fgets(str, 120, fp);
printf("%s", str);
}

return 0;
}



And the damn error continues..
Please, can you compile this code and see if it generates error to you too?

Thanks again.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Quote:
Original post by Maquiavel
Now I'm trying with>

*** Source Snippet Removed ***

And the damn error continues..
Please, can you compile this code and see if it generates error to you too?

Thanks again.


Look again at what your code is doing. This line:

> char *str;

allocates a pointer to a char element. Where is this pointer actually *pointing to*? It could be anywhere! Should you dereference the pointer to write a char like this:
> *str = 'a';

You *can* but since str can be pointing anywhere, you could overwrite data in other variables or generate a segmentation fault (a memory access error). If you had done something like this:

> str = new char;

then the previous statement would be safe. But then, this statement would not:

> strcpy( str, "ab" );

In this statement, you're writting 2 characters (possibly 3 counting the null terminator at the end of "ab") to the location which only has 1 byte (a char) allocated.

The best practice is to define a buffer to read in the characters you want. You can use str as declared if you are only outputting.

> char *str = "Programacao em C...\nAprendendo a programar em C, para partir\nà programação de jogos!\n";
> fputs(str, fp);

To read in characters, define a buffer of the size you want to read in.

> char buffer[50];
> ...
> while (!feof(fp))
> {
> fgets(buffer, 50, fp); // reads in up to 50-1 characters, appends with null character
> printf("%s", buffer);
> }

When working with C/C++, you need to be very careful when working with pointers/arrays to prevent writing to illegal memory locations.

Hope this helps.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!