• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Randall Perkins

Logic error in my code i think

17 posts in this topic

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

Edited by MrPhoenix
0

Share this post


Link to post
Share on other sites

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

1

Share this post


Link to post
Share on other sites

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.

2

Share this post


Link to post
Share on other sites

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;
    }
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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 ?

0

Share this post


Link to post
Share on other sites
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?
0

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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 -

 

0

Share this post


Link to post
Share on other sites

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 

0

Share this post


Link to post
Share on other sites

A couple of points:

[list]

[*] Your code contains no error handling.

[list]

[*] What if the file is missing?

[*] What if the file is corrupt?

[/list]

[*] When dynamically allocating a structure, simply malloc(sizeof(some_structure)).

[list]

[*] 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.

[/list]

[*] 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".

[/list]

 

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
0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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:

[code]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 }  [/code]

 

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:

[code]  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.     } }[/code]

 

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.

1

Share this post


Link to post
Share on other sites

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

0

Share this post


Link to post
Share on other sites

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  
Followers 0