Jump to content

  • Log In with Google      Sign In   
  • Create Account

FREE SOFTWARE GIVEAWAY

We have 4 x Pro Licences (valued at $59 each) for 2d modular animation software Spriter to give away in this Thursday's GDNet Direct email newsletter.


Read more in this forum topic or make sure you're signed up (from the right-hand sidebar on the homepage) and read Thursday's newsletter to get in the running!


Logic error in my code i think


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
17 replies to this topic

#1 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 01:20 AM

This is the file 

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

    typedef struct {
        char map_title[68];
        int width,height;
        char map_tiles[100][100];
    } map_file;


    char *readFile(char *fileName) {
      FILE *file;
      char *code = malloc(1000 * sizeof(char));
      char *p = code;
      file = fopen(fileName, "r");
      do
      {
        *p++ = (char)fgetc(file);
      } while(*p != EOF);
      *p = '\0';
      return code;
    }

    map_file *load_map(char *location) {
        printf("Loading map : %s \n", location);

        map_file *tehMap;
        char *dataToken,*map_data;

        map_data = readFile(location);

            dataToken = strtok(map_data,",");

            printf("STARTED TOKEN OUTPUT\n");
            while(dataToken != NULL) {
                printf("TOKEN : %s \n",dataToken);
                dataToken = strtok(NULL,",");
            }
            printf("FINISHED TOKEN OUTPUT\n");


        return tehMap;
    }


int main()
{
    printf("Map engine testing ground for logic\n\n");

    map_file *theMap;
    theMap = load_map("map.txt"); // i plan on using the function to assign the values from the file to the struct

    return 0;
}

 

 and ill attach map.map so you have something to test with, but my issue is in stdout only like half of the map file is output im not sure if it a char error of something in the strtok function.

 

any tips or help would be mean a lot, thank you for your time smile.png

Attached Files

  • Attached File  map.txt   2.32KB   37 downloads

Edited by MrPhoenix, 21 January 2013 - 01:21 AM.


Sponsor:

#2 Washu   Senior Moderators   -  Reputation: 5457

Like
1Likes
Like

Posted 21 January 2013 - 01:42 AM

First off, you have a nasty buffer overrun issue when your map reading code.


In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.
ScapeCode - Blog | SlimDX


#3 Olof Hedman   Crossbones+   -  Reputation: 2953

Like
3Likes
Like

Posted 21 January 2013 - 01:53 AM

Your map.txt is 2KB large, and you try to read it into a 1000 byte big buffer



#4 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 02:11 AM

how would anyone recommend in using malloc when the size of the file will change depending on the map ???????



#5 Olof Hedman   Crossbones+   -  Reputation: 2953

Like
2Likes
Like

Posted 21 January 2013 - 02:19 AM

Either you check the size of the file and allocate that amount, or you process the file in parts if you can't (or don't want to) fit the whole file in memory.



#6 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 02:36 AM

i tryed this but i think the malloc function is making the program crash

 

    static int fsize(FILE *fp){
        int prev=ftell(fp);
        fseek(fp, 0L, SEEK_END);
        int sz=ftell(fp);
        fseek(fp,prev,SEEK_SET); //go back to where we were
        return sz;
    }

    char *readFile(char *fileName) {
      FILE *file;
      char *code;
      int sizeFile;

      file = fopen(fileName, "r");
      sizeFile = fsize(file);
      printf("Size of file : %i \n", sizeFile);
 //     code = malloc(sizeFile * sizeof(char));
      code = malloc(sizeFile);
      char *p = code;

      do {
        *p++ = (char)fgetc(file);
      } while(*p != EOF);

      *p = '\0';
      return code;
    }


#7 Khatharr   Crossbones+   -  Reputation: 3040

Like
0Likes
Like

Posted 21 January 2013 - 02:36 AM

Nothing's jumping out at me apart from the fact that you don't test the return from fopen(). If you walk through it with the debugger can you see anything unusual (such as a negative 1 from fsize() getting passed to malloc())?

Edited by Khatharr, 21 January 2013 - 02:42 AM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#8 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 02:45 AM

Nothing's jumping out at me apart from the fact that you don't test the return from fopen(). If you walk through it with the debugger can you see anything unusual (such as a negative 1 from fsize() getting passed to malloc())?

 

Khatharr it happens at the malloc function

i tested the fsize functions it returns 2374 for the file so that means the file is open and return a size

so after checking everything i have to be doing the malloc wrong ?



#9 Khatharr   Crossbones+   -  Reputation: 3040

Like
0Likes
Like

Posted 21 January 2013 - 02:49 AM

A call to malloc() should not result in an instant crash unless some corruption is happening somewhere. Does the program just immediately fail or does malloc() return NULL?
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#10 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 02:53 AM

Khatharr it fails at the do { } 

i tested it by doing this 

    static int fsize(FILE *fp){
        int prev=ftell(fp);
        fseek(fp, 0L, SEEK_END);
        int sz=ftell(fp);
        fseek(fp,prev,SEEK_SET); //go back to where we were
        return sz;
    }

    char *readFile(char *fileName) {
      FILE *file;
      char *code;
      int sizeFile;

      file = fopen(fileName, "r");
      sizeFile = fsize(file);
      printf("Size of file : %i \n", sizeFile);
 //     code = malloc(sizeFile * sizeof(char));
      code = malloc(sizeFile * sizeof(char));
      printf("Test for after malloc\n");
      char *p = code;
      printf("after sign pointer to code which is malloc");
      do {
        *p++ = (char)fgetc(file);
      } while(*p != EOF);
      printf("after the do function\n");
      *p = '\0';
      return code;
    }

 

the console gets to "after sign pointer to code which is malloc" and quits after that



#11 Khatharr   Crossbones+   -  Reputation: 3040

Like
0Likes
Like

Posted 21 January 2013 - 03:00 AM

Ah, you're casting the return value of fgetc() to a char and then testing that against EOF. If the comparison fails then you won't break the loop on EOF and you end up with an overrun. Accept the value of fgetc() as its native type and then test it against EOF, then write to the buffer based on the result.

Just out of curiosity, why not just use fread() here?

Remember to close your FILE pointer when you're done or you'll leak handles.

When you acquire a resource (opening a file or allocating memory, etc) it's important to test for success before continuing and it's important to remember to release the resource when you're done with it.

Oh, and:

*p = '\0';

Could just be:

*p = 0;

But if you're going to write an extra byte like that then you need to increase the allocation size by 1.

Ah, I was so busy looking for the bug I didn't realize - when you do things like this you should use the properties of the destination (length or boundary positions) to control the loop rather than the properties of the source.


Edited by Khatharr, 21 January 2013 - 03:40 AM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#12 Acid-Chris   Members   -  Reputation: 500

Like
0Likes
Like

Posted 21 January 2013 - 04:24 AM

There is so much wrong in these 3 functions.

 

But one of the biggest issues, besides all the other ones the previous posters mentioned is in your load_map function:

 

map_file *tehMap;


[some weird code here]


return tehMap;

 

 

and thats it? you do nothing with this? no allocation, no assignment of your map data?

There are so many more ways to read your map data, many more EASIER ways. You can read your 100x100 grid all at once, the just use a memcpy or whatever. Why parse it in such a strange way?

You could simply read the whole map_file struct all at once if you had saved it properly.

 

Your comment is nice:

"// i plan on using the function to assign the values from the file to the struct"

but...you never do that!!

 

Please, do yourself a favour and THINK STEP BY STEP on what you do. To me, this looks like you copy and pasted fragments of map loading code you found on google into your program.

 

No offence mate, but please start with a smaller map!  Use a grid of 5x5 tiles for example where you easily can check all contents of the array in the DEBUGGER. If your loading code works, it doesnt matter if you're using a 5x5 or 1000x1000 map.

 

Good luck,

- Christoph -

 



#13 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 05:18 AM

Acid-Chris  

i do plan on adding the data to the struct and i don't take any offence im here to learn off my mistakes

 

i write 90% of the code my self, i do copy some minor functions from the internet i find and think will work for the purpose i need them to do

 

right now im working on the struct, im trying to load the map data in to the int array now but the program freezes now

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <sys/stat.h>

    typedef struct {
        char *map_title;
        int width,height,aot,tiles[1000];
    } map_file;

    static int fsize(FILE *fp){
        int prev=ftell(fp);
        fseek(fp, 0L, SEEK_END);
        int sz=ftell(fp);
        fseek(fp,prev,SEEK_SET); //go back to where we were
        return sz;
    }

    static char *readFile(char *fileName) {
      FILE *file;
      char *code;
      int sizeFile;
      file = fopen(fileName, "r");
      sizeFile = fsize(file);
      printf("Size of file : %i \n", sizeFile);
      code = malloc(sizeFile * sizeof(char));
      printf("Test for after malloc\n");
      fread(code, 1, sizeFile, file);
      fclose(file);
      return code;
    }

    // load a map file in to the struct
    map_file *load_map(char *location) {
        printf("Loading map : %s \n", location);


        map_file *tehMap;
        tehMap = malloc(3*sizeof(map_file*));
        char *dataToken,*map_data;
        int count = 1,tile_count = 0;

        map_data = readFile(location);
        dataToken = strtok(map_data,",");
            printf("STARTED TOKEN OUTPUT\n");
            while(dataToken != NULL) {

                if(count == 1) {
                    strcpy(tehMap->map_title,dataToken);
                } else if(count == 2) {
                    tehMap->width = atoi(dataToken);
                }else if(count == 3) {
                    tehMap->height = atoi(dataToken);
                }else if(count > 3) {
                    tehMap->tiles[tile_count] = atoi(dataToken);
                    tile_count += 1;
                }

                printf("TOKEN : %s \n",dataToken);
                dataToken = strtok(NULL,",");
                count++;
            }

            tehMap->aot = count - 3;

            printf("Amount of map inputs : %i \n", count);
            printf("FINISHED TOKEN OUTPUT\n");
            printf("tehMap struct -> Map title  : %s \n", tehMap->map_title);
            printf("tehMap struct -> Map width  : %i px \n", tehMap->width);
            printf("tehMap struct -> Map height : %i px \n", tehMap->height);
            printf("tehMap struct -> Map aot    : %i px \n", tehMap->aot);

            /* for displaying the map data from the file to the console
                for(int s=0; s < tehMap->aot; s++) {
                    printf("%i,",tehMap->tiles[s]);
                }
            */

        return tehMap;
    }


int main()
{
    printf("Map engine testing ground for logic\n\n");

    map_file *theMap;
    theMap = malloc(3*sizeof(map_file*));
    theMap = load_map("map.map");

    return 0;
}

 

 

any advice would be nice or modifications, thanks for the input 



#14 rip-off   Moderators   -  Reputation: 8762

Like
0Likes
Like

Posted 21 January 2013 - 05:30 AM

A couple of points:

  • Your code contains no error handling.

    • What if the file is missing?

    • What if the file is corrupt?

  • When dynamically allocating a structure, simply malloc(sizeof(some_structure)).

    • Your code tries to mallocate 3 times the size of a pointer to the structure, which makes no sense unless you are trying to dynamically allocate an array of 3 pointers to structures.

  • You are trying to strcpy() into an uninitialised pointer - tehMap->map_title.

  • It might be easier to use fscanf() than string tokenisation, at least for the file "header".

 

Consider building your program in smaller chunks. First write a function that will print the contents of a file to the screen. Test this function, ensure it works and handles any edge cases (file not found) gracefully.

 

Next write a function to parse the file format, but continue to print it to the screen. Test it with a minimal correct file. Harden the function against unexpected input (e.g. an empty file, not enough fields, non-numeric data in numeric field, etc, etc). Test it with more advanced files.

 

Next, create the structure to represent the data in memory. Test this by filling the structure in code, and print it to the screen.

 

As the final step, try to fill the structure from the data in the file.


Edited by rip-off, 21 January 2013 - 05:48 AM.


#15 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 05:56 AM

rip-off i changed the code around a lot but it freezes when i try to store the data from the char to the int tiles[1000] in the struct

 

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <sys/stat.h>
 
    typedef struct {
        char *map_title;
        int width,height,aot,tiles[1000];
    } map_file;
 
    static int fsize(FILE *fp){
        int prev=ftell(fp);
        fseek(fp, 0L, SEEK_END);
        int sz=ftell(fp);
        fseek(fp,prev,SEEK_SET); //go back to where we were
        return sz;
    }
 
 
    static char *readFile(char *fileName) {
      FILE *file;
      char *code;
      int sizeFile;
      file = fopen(fileName, "r");
      sizeFile = fsize(file);
      printf("Size of file : %i \n", sizeFile);
      code = malloc(sizeFile * sizeof(char));
      printf("Test for after malloc\n");
      fread(code, 1, sizeFile, file);
      fclose(file);
      return code;
    }
 
    // load a map file in to the struct
    map_file *load_map(char *location) {
        printf("Loading map : %s \n", location);
 
        map_file *tehMap;
        tehMap = malloc(sizeof(map_file*));
        char *dataToken,*map_data;
        int count = 1,tile_count = 1;
 
        map_data = readFile(location);
        dataToken = strtok(map_data,",");
            printf("STARTED TOKEN OUTPUT\n");
            while(dataToken != NULL) {
 
                if(count == 1) {
                    tehMap->map_title = dataToken;
                } else if(count == 2) {
                    tehMap->width = atoi(dataToken);
                }else if(count == 3) {
                    tehMap->height = atoi(dataToken);
                }else if(count > 3) {
                    tehMap->tiles[tile_count] = atoi(dataToken); // <------------- where it freezes
                    tile_count += 1;
                }
 
                printf("TOKEN : %s \n",dataToken);
                dataToken = strtok(NULL,",");
                count++;
            }
 
            tehMap->aot = tile_count + 1;
 
            printf("Amount of map inputs : %i \n", count);
            printf("FINISHED TOKEN OUTPUT\n\n");
            printf("tehMap struct -> Map title  : %s \n", tehMap->map_title);
            printf("tehMap struct -> Map width  : %i px \n", tehMap->width);
            printf("tehMap struct -> Map height : %i px \n", tehMap->height);
            printf("tehMap struct -> Map amount of tile    : %i \n", tehMap->aot);
 
 
        return tehMap;
    }
 
 
int main() {
    printf("Map engine testing ground for logic\n\n");
    map_file *theMap = NULL;
    theMap = load_map("map.map");
    return 0;
}

Edited by MrPhoenix, 21 January 2013 - 05:58 AM.


#16 rip-off   Moderators   -  Reputation: 8762

Like
1Likes
Like

Posted 21 January 2013 - 06:23 AM

You haven't really addressed many of the issues I highlighted earlier.

 

You still are not allocating the map structure correctly. You are only allocating the sizeof a pointer. Alternatively, avoid dynamic allocation.

 

One option is to declare the map on the stack, and return it by value:

map_file load_map(char *location) {
    map_file result;
    // Load the data
    return result;
}
 
int main() {
    map_file map = load_map("map.map");
    // Use the map
}
 

 

A common C idiom is to get the caller to allocate the object, and pass a pointer to it for it to be filled in. This is particularly nice because it lends itself to error reporting via the return value:

 
int load_map(map_file *result, char *location) {
    // Try load some data
    if(someError) {
        return 0;
    }
    // Try load more data
    return 1;
}
 
int main() {
    map_file map;
    if(load_map(&map, "map.map")) {
        // Use the map
    } else {
        // Alert the user or otherwise handle the error gracefully.
    }
}

 

I've noticed two other errors in your code, you fail to handle the case where malloc() returns NULL, and you appear to start your tile indexing at "1". Array indices start at "0" in C.



#17 Khatharr   Crossbones+   -  Reputation: 3040

Like
0Likes
Like

Posted 21 January 2013 - 06:31 AM

Take it easy, Chris. People come here to learn. There's a lot to take in when you're new. He'll catch up over time.


void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#18 MrPhoenix   Members   -  Reputation: 134

Like
0Likes
Like

Posted 21 January 2013 - 06:36 AM

rip-off i fixed the problem and followed more of your highlighted information :) it works and i have the if conditions to check if a file loaded or not and so on

 

 

and Khatharr thank you






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS