Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

What gives?

Name: Anonymous 2010-01-17 10:09

I have a text file called bigint that reads:

3
1 8888888888 2222222222
2 9999999999 10000000000
2 10000000000 9999999999


Yet everytime I run the following code:


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

int main(){
   
    FILE *ifp;
    char* LOLSTRING;
    int lawl, lawl2;
   
    ifp = fopen("bigint.txt", "r");
   
    fscanf(ifp, "%d", &lawl);
    fscanf(ifp, "%d", &lawl2);
    fscanf(ifp, "%s", LOLSTRING);
   
    printf("%s\n", LOLSTRING);
   
    fclose(ifp);

    system("pause");

    return 0;
}


... the program crashes AFTER the pause is run. Meaning, whenever I press any key, it somehow shits itself. What gives?

Name: Anonymous 2010-01-17 10:19

I know it has something to do with assigning memory to the character array, but why does it fuck up only after it does its part?

Name: Anonymous 2010-01-17 10:20

>>1
I see a couple of problems:
    char* LOLSTRING;
You need to alloc that string somewhere, otherwise fscanf will write to random memory. fscanf itself isn't even safe, as you could read in a string bigger than your alloced memory, thus making your program suspectible to a heap or stack overflow(depending on how you alloc it)
  system("pause");
Is this necesarry? Run your application from a command line interface, terminal or whatever.
  ifp = fopen("bigint.txt", "r");
You're not checking the return value here, file bigint.txt may not exist or it may already be open or something of that sort.

Name: Anonymous 2010-01-17 10:24

I run it from DevC++, writing system("pause"); or getchar() is just the way I've been taught.

Also, this isn't a real program or assignment, just something I cooked up to test something I noticed while doing something else, so I already know the file is there and functional.

Name: Anonymous 2010-01-17 10:31

This all sucks but the easiest way to fix it is probably changing char* LOLSTRING; to char LOLSTRING[9001]; and then passing it as &LOLSTRING (or maybe arrays *ARE* pointers, I don't remember. Just try with and without &)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List