Sign in to follow this  

Problem with C streams..

This topic is 4862 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
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
Now all the things are clear. I was testing the code on DevC++. So, now I tested it on VS .NET, it had compiled and the error was generated, hence I started debugging. The file "fgets.c" that contains the source code for the function fgets has been opened. What it really does is change the string char by char by this code:
if ((*pointer++ = (_TSCHAR)ch) == _T('\n'))

The same as:

char name[10] = "C Programming";
/* Changing */
name[0] = 'A';
name[1] = 'L';


Ok, no problem until here.

char* str = "C Programming"; is a pointer to a CONST string. We can change to where this pointer point to, but we can't change this string. And was this I was trying to change. The function fegts was trying this: str[0] = 'B'; str[1] = 'A'; ...

If fgets would do: str = "New string" it would work, because it would only changing where str points to.

Cya.

Share this post


Link to post
Share on other sites

This topic is 4862 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this