-1

The code below deletes the contents of game.answer in the future and I can't figure out why.

This is the structure:

typedef struct
{
   int guesses, guessesAllowed;
   char* answer;
   char max;
} GameState;

And this is my function to build a new structure:

GameState makeGame(int guessesAllowed, int numOfPositions, char max,
   int seed)
{
   GameState game;
   char answer[9];

   answer[0] = '\0';

   game.guesses = 0;
   game.guessesAllowed = guessesAllowed;
   game.answer = answer;
   game.max = max;

   getAnswer(answer, numOfPositions, max, seed);

   return game;
}

I figure it something to do with overriding memory it shouldn't?

Zach
  • 237
  • 4
  • 16
  • 1
    You have a structure containing a pointer. I assume you have properly initialized that pointer? That it points to some in-scope and allocated memory? And can you please try to create a [Minimal, ***Complete***, and Verifiable Example](http://stackoverflow.com/help/mcve) to show us (and also copy-paste the complete input and output of the program, together with the *expected* output)? – Some programmer dude Sep 25 '17 at 07:24
  • 1
    You didn't allocate any memory for `game.answer`. You can use `strdup` the first time you input something, and then compare new string length, if length < initial length, use `strcpy` else `strdup`. `strdup` allocates memory for you and copies the string – TDk Sep 25 '17 at 07:34
  • You haven't given us a [MCVE]. Is it a ***complete*** example? – iBug Sep 25 '17 at 07:36
  • @TheophileDano I just edited my function that I use to create my GameState. If I'm not mistaken I believe this does allocate memory for the game answer. – Zach Sep 25 '17 at 07:39
  • 3
    @Zach the problem in your "makeGame" function is that you do not heap-allocate your string. `char answer[9];` is just 9 bytes allocated on the stack. Bytes that will later be deleted when the function returns – TDk Sep 25 '17 at 07:41

1 Answers1

2

You can't do this:

game.answer = answer;

You declared answer as an array in a function. You are not allowed to keep that address and return it.

The memory of your function and the variables used in it, like answer are immediately reused and overwritten.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • It would be useful if you cite the standard chapter that specifies variable scope and lifetime. It is located at *6.2.4 Storage durations of objects* in [this draft document](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf). – Jorge Bellon Sep 25 '17 at 07:51