using malloc for block of structs - c

I am trying to allocate a block of memory, and store a list of structures without using multiple mallocs for each... this is just a generic example, I don't have the original code I was working with earlier, but this is the general idea, but my problem was that I was getting heap corruption when other parts of my code executed after the InitPoints() function call. I don't know what part of my code is illegal, but I suspect it is in the for loop of the InitPoints() function. I am trying to use this as table, then I can create additional tables of defined size if I ran out of memory and link them together... so kind of like a dynamic expanding array if that makes any sense.
typedef struct Tb{
POINT points;
POINT *next;
} TABLE;
typedef struct Pt{
int x;
int y;
}POINT;
POINT *mypoints;
int main() {
int size = 10;
int i = 0;
mypoints = InitPoints(size);
for(i=0; i < size; i++)
{
printf("mypoint [%d] = (%d,%d)\n",i, mypoints->x, mypoints->y);
mypoints = mypoints + sizeof(POINT);
}
// some other code...
// i.e. createThread(....)
return 0;
}
POINT* InitPoints(int size)
{
POINT *tmp;
POINT *orig;
int a = 10;
int b = 1000;
orig = (POINT*) malloc (sizeof(POINT) * size);
if(orig == NULL)
return NULL;
tmp = orig;
for (i = 0; i < size; i++)
{
tmp->x = a++;
tmp->y = b++;
tmp = tmp + sizeof(POINT);
}
return orig;
}

This is wrong:
mypoints = mypoints + sizeof(POINT);
You should review pointer arithmetic in C. Just use:
mypoints += 1; /* or something similar */
(There is a similar problem in your InitPoints function)
Here's one referemce:
http://www.eskimo.com/~scs/cclass/notes/sx10b.html

The problem is in this line:
tmp = tmp + sizeof(POINT);
It should be
++tmp;
The latter says to increment the pointer by one element; since it points to the structure, it increments by the size of the structure. The original code instead increments by n elements where n is the number of bytes in the structure. For example, if int is 32-bits, it will advanced by 8 elements.

This is why I would do it
for (i = 0; i < size; i++)
{
orig[i].x = a++;
orig[i].y = b++;
}

In C, adding an integer to a POINT* pointer advances the pointer not by that number of bytes, but by that number of POINT structures.
You have two places in your code where you add sizeof(POINT) to your pointer. Instead you should just add 1.

Related

How to use Malloc pointers in comparison to array in C

I created a struct called PLAYER and I want to create an list that stores the pointers to the PLAYER object.
If I want to accomplish it with
PLAYER **ptr = malloc(10*sizeof(PLAYER *));
How can I assign the pointers to each index? I tried:
PLAYER *a;
PLAYER *b;
ptr[0] = a;
ptr[1] = b;
1.This seems to work. Can I get some explanation on the memory address behind it?
I also tried:
ptr = a;
//increase the address and assign b
ptr += sizeof(PLAYER *);
ptr = b;
2.This does not work correctly I think. Can I see a correct way of assign the list without using the [] brackets?
3.If I allocate only one entry's size and assign multiple ones:
PLAYER **ptr = malloc(1*sizeof(PLAYER *));
ptr[0] = a;
ptr[1] = b;
I can get these PLAYER object by using ptr[0] ptr[1], but will this cause any problems like overwrite other memories?
4.If I use [] brackets, do I need to malloc at each index in order to use it?
PLAYER *ptr[10];
for(int i = 0; i < 10; i++)
ptr[i] = malloc(sizeof(PLAYER *));
5.Do I need to free an array after using it? such as:
char ptr[10] = "abc";
//do something with ptr
free(ptr);
char *ptr2[10] = {"123", "abc"};
free(ptr2);
Any help would be much appreciated!
If you have a PLAYER **ptr = malloc(10*sizeof(PLAYER *));
That means you have to malloc for every ptr[i] = malloc(sizeof(PLAYER));
Accessing the array at indexes would be ptr[i]->somevalue
NOTE: if you have pointers inside the struct you need to allocate for those as well!!
Freeing your memory would be:
for(int i = 0; i<10;i++){
free(ptr[i]->anyAllocatedPointersInside);
free(ptr[i]);
}
free(ptr);
SPECIFICALLY IN THAT ORDER
If you update the post with the full struct I can update mine to more accurately help you.
When in doubt, think of malloc() allocations in these terms: it allocates raw memory, and it doesn't know anything about your structs!
When you think in these terms, you'll get it right.
Let's try to answer to your questions:
You are basically instancing within the stack a pointer, with any content into it, just as int hello;. That integer can contain anything, because you don't set it as in int hello = 2;. The same thing is happening with your pointers: int * hello; will be a pointer (to an integer) that can contain any address. Hence, if you dereference a pointer like that, your chances to get caught into SIGSEGV are not low.
Then, once you have created those pointers that can be anything, you're assigning their address to the pointer of pointers array you've allocated. Don't do that.
That doesn't work correctly, because if you have an array of pointers to a given type, you can simply increment with += n, the compiler will calculate the appropriate "sizeof(type_you're-pointing_to)" and will add that automatically. This is the main purpose of declaring a pointer to a given type.
You're effectively overwriting other memory.
Brackets are just pointer dereferencing: *ptr+n same as ptr[n].
You need to free each line, and then the array of pointers of pointers.
Basically every pointer you get with malloc(), you have to free it with free(). DO NOT call free() to any other pointers that hasn't been spit out from malloc().
Let me show you some code I have just written to show you better:
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // for memset
#define N_POINTERS 4
#define M_PLAYERS_PER_LINE 3
struct PLAYER
{
int id;
int score;
int age;
};
int
main()
{
// Allocate the array of pointers, big enough to old N pointers.
struct PLAYER ** pointers = malloc(N_POINTERS*sizeof(struct PLAYER*));
// Always better zeroize pointers arrays.
memset(pointers, 0, N_POINTERS*sizeof(struct PLAYER *));
// Allocate each line of M `PLAYER` structs.
// Basically we allocate N chunks of memory big enough to contain M PLAYER structs one next each other.
// What we get is something like this:
//
// pointer pointers PLAYER lines
// of pointers array
// [addrP] -> [addr0] -> [PLAYER0 PLAYER1 PLAYER2] .. M
// [addr1] -> [PLAYER0 PLAYER1 PLAYER2] .. M
// ...N
//
int id = 0;
for (int i = 0; i < N_POINTERS; ++i)
{
pointers[i] = malloc(M_PLAYERS_PER_LINE*sizeof(struct PLAYER));
// Set the data you want to the structs.
for (int k = 0; k < M_PLAYERS_PER_LINE; ++k)
{
pointers[i][k].id = id++;
pointers[i][k].score = 123 + k;
pointers[i][k].age = 33 + i;
}
}
// Print data.
// Here we use a single PLAYER pointer that will
// traverse the entire PLAYER matrix.
struct PLAYER * player;
for (int i = 0; i < N_POINTERS; ++i)
{
for (int k = 0; k < M_PLAYERS_PER_LINE; ++k)
{
// Assign the current PLAYER to our pointer.
player = pointers[i] + k;
// Print PLAYER data, by reading the pointed struct.
printf("Player: #%i age:%i score:%d\n", player->id, player->age, player->score);
}
}
// Deallocate!
for (int i = 0; i < N_POINTERS; ++i)
{
// Deallocate each line chunk.
free(pointers[i]);
}
// Deallocate the array of pointers.
free(pointers);
return 0;
}
As a bonus track, if you need to allocate a matrix of M*N PLAYER structs, you should also look at this code, that will allocate M*N PLAYER structs into one unique memory block, one next each other, which is much more easier to manage, as you can see by the code itself:
#include <stdlib.h>
#include <stdio.h>
#define LINES 4
#define COLUMNS 3
#define GET_ARRAY_POS(lin, col) (col+(lin*COLUMNS))
struct PLAYER
{
int id;
int score;
int age;
};
int
main()
{
// Allocate a *FLAT* array of PLAYER structs, big enough to
// contain N*M PLAYER structs, one next each other.
struct PLAYER * array = malloc(LINES*COLUMNS*sizeof(struct PLAYER));
// Set the data you want to the structs.
int id = 0;
for (int lin = 0; lin < LINES; ++lin)
{
for (int col = 0; col < COLUMNS; ++col)
{
int pos = GET_ARRAY_POS(lin, col);
array[pos].id = id++;
array[pos].score = 123 + col;
array[pos].age = 33 + lin;
}
}
// Print data.
// Here we use a single PLAYER pointer that will
// traverse the entire PLAYER matrix.
for (int i = 0; i < (LINES*COLUMNS); ++i)
{
// Print PLAYER data, by reading the pointed struct.
printf("Player: #%i age:%i score:%d\n", array[i].id, array[i].age, array[i].score);
}
// Deallocate!
free(array);
return 0;
}
Enjoy! ^_^

realloc() invalid old size on struct arrays

I have been assigned to make a functioning student election program for our school defense (and probably for actual use ... ). However I've been stuck with a problem for a while now.
My goal is to make a flexible array of structs, since I can't use an arbitrary limitation, also arrays have a 99-item limit for me (*see end of the post). I have used realloc() but it gives an abort() for invalid old size. BUT, I have tried testing a dynamic struct array in another program and it worked flawlessly. I can't figure out what's causing the other one to crash.
My election program (i.e. the crashing one):
NOTE: entr_cmd function just moves the cursor to the bottom of the screen and prints a text, and STREQL just see if two string matches, just a shortcut macro for strcmp
struct candidate {
long lrn;
char *name;
int grade;
char *section;
char *party;
char *position;
}
**candidates,
// :: Temporary Array for storing all the candidates in the position to be voted in
**candidates_cur;
int can_c = 0;
[...]
int main() {
[...]
candidates = malloc(2 * sizeof(struct candidate *));
[...]
if(STREQL(command, "c")) {
struct candidate *c;
if(can_c > 1) {
struct candidate **tmp;
tmp = (struct candidate**) realloc(candidates, (1 + can_c) * sizeof(struct candidate *));
if(tmp != NULL) candidates = tmp;
}
candidates[can_c - 1] = malloc(sizeof(struct candidate *));
c = candidates[can_c - 1];
entr_cmd("Candidate's Name: ");
// :: This recieves the input but replaced for testing
c->name = malloc(4 * sizeof(char));
strcpy(c->name, "XXX");
can_c++;
}
[...]
The test program that works flawlessly:
this generates a random string of numbers for the members of the test struct
struct test {
char *name;
char *another;
int test;
} **arr;
int main() {
int r1;
arr = malloc(2 * sizeof(struct test *));
r1 = rand() % 45;
for(int i = 0; i < r1; i++) {
int r2 = rand() % 22;
if(i > 2) {
struct test **data;
data = (struct test**) realloc(arr, (2 + i) * sizeof(struct test*));
if(data != NULL) {
arr = data;
}
}
arr[i] = malloc(sizeof(struct test *));
struct test *t = arr[i];
t->name = malloc(r2 * sizeof(char));
t->another = malloc(r2 * sizeof(char));
t->test = r2;
for(int ii = 0; ii < r2; ii++) {
t->name[ii] = (char) (rand() % 9) + '0';
t->another[ii] = (char) (rand() % 9) + '0';
}
printf("====[%u]====\n%s\n%s\n%u\n", i, arr[i] -> name, arr[i] -> another, arr[i] -> test);
}
for(int i = 0; i < r1; i++) {
free(arr[i]->name);
free(arr[i]->another);
free(arr[i]);
}
free(arr);
getch();
}
Any help would be appreciated as our teacher had put great expectation upon me and told me this was going to be easy easy but it's proving itself to be the opposite.
Thank you for reading and have a nice day!!!
extra non-sense: I'm in a course where we use TurboC++ regularly for programming, but it's pretty hard to do it there, so I instead used C99 with my neovim setup so I can have fast navigation and also most of the things in C99 can work in TurboC++. In other words, I can't really work with (recent standard) C++, if so, I think I would have probably done this more easily
The problem is not related to memory allocation at all! The problem occurs because I keep allocating candidates[-1], i had put candidates[can_c - 1] to candidates[can_c] memory.
Thank you for everyone who helped! (and #someprogrammerdude for pointing it out)

c loop through struct array in reverse

I'm trying to loop through an array of structs in reverse, not quite sure how to go about it. This is how I'm looping through normally:
struct Thing* ptr = things;
struct Thing* endPtr = things + sizeof(things)/sizeof(things[0]);
for(ptr < endPtr)
{
// do stuff
}
Assuming N >= 0, the item-magnitude of your things sequence , you can use indexes, of course, but really you simply need a single pointer:
struct Thing *ptr = things + N;
while (ptr != things)
{
--ptr;
// do something with *ptr;
}
This can be a possible solution
// assuming 'Thing' is the structure in question and 'size' is the length of array
struct Thing array[size]; // created an array of structure Thing having length equals size
struct Thing *ptr; // pointer of type struct Thing
ptr = array;
ptr = ptr + (size-1); // point the pointer to last element of the array
int i; //counter
for( i=0; i < size; i++ )
{
// do something with the pointer ptr
ptr--;
}
It is possible to use pointers in a down-counting loop, but I would instead prioritize readability:
size_t size = sizeof(things) / sizeof(things[0]);
for(size_t i=0; i<size; i++)
{
size_t index = size - i - 1;
things[index] = something;
}

dynamically increase size of array (int*) in c

i want to dynamically add numbers to an array in c. My idea is to just allocate a new array with size + 1, add the number, free the root array and change the pointer from the temp to the root array. Like this:
void addNumber(int* a, int* size, int number)
{
*size = *size + 1;
int* temp = (int*)(calloc(*size, sizeof(int)));
int i, j = 0;
for(i = 0; i < *size-1; i++) {
if(a[i] < number) {
printf("add ai");
temp[j] = a[i];
j++;
} else {
printf("add number");
temp[j] = number;
}
}
if(j != *size) {
printf("add new number");
temp[j] = number;
}
free(a);
a = temp;
}
int main(int argc, char* argv[])
{
int n = 10;
int* a;
int size = 1;
a = (int*) (calloc(1, sizeof(int)));
a[0] = 1;
if(!contains(a, size, 2)) {
addNumber(a, &size, 2);
}
printArray(a,size);
return 0;
}
The problem is that in the addNumber function the code works and the *a has the right values of the new array. But in the main function the array *a has the values 1,0. So the new inserted value 2 is not added. Why? Can't get the reason.
To dynamically change the array size, you can use the realloc() routine. Apart from being eaiser to use, it can be faster than the approach of calling free() and malloc() sequentially.
It is guaranteed the reallocated block will be populated with the content of the old memory block.
The problem is that in the addNumber function the code works and the *a has the right values of the new array
There are two major flaws in your code. The first is that you your addNumber() routine doesn't return the newly allocated memory block (thus it is being leaked), you should either use double pointer or return the new block as function result.
And the second one results from the first - after a has been freed, you continue to write to it.
If you prefer to stick to your current approach, this modified code should work:
void addNumber(int** a, int* size, int number)
{
*size = *size + 1;
int* temp = (int*)(calloc(*size, sizeof(int)));
int i, j = 0;
for(i = 0; i < *size-1; i++) {
if((*a)[i] < number) {
printf("add ai");
temp[j] = (*a)[i];
j++;
} else {
printf("add number");
temp[j] = number;
}
}
if(j != *size) {
printf("add new number");
temp[j] = number;
}
free(*a);
*a = temp;
}
int main(int argc, char* argv[])
{
int n = 10;
int* a;
int size = 1;
a = (int*) (calloc(1, sizeof(int)));
a[0] = 1;
if(!contains(a, size, 2)) {
addNumber(&a, &size, 2);
}
printArray(a,size);
return 0;
}
What you're looking for is realloc(). It can be used to grow or shrink memory while retaining its contents.
/* array is now sizeof(int) * new_size bytes */
array = realloc(array, sizeof(int) * new_size);
realloc() might change the existing memory allocation, or it might allocate a whole new block of memory. This is why it's important to reassign the result back to the thing being reallocated.
But if addNumber() reallocates the array by making new memory, main() won't know it. This is for the same reason this doesn't work.
void incrementNumber(int num) {
num = num + 1;
}
int num is a number that gets passed by value. If you want it to be reflected in the caller, you need to pass it as a pointer.
void incrementNumber(int *num) {
*num = *num + 1;
}
Pointers are the same way. They're still numbers. int *a passes a pointer by value. If you change a in addNumber it won't be seen by the caller. Just like before, you need to pass it as a pointer. A pointer to a pointer used like this is known as a double pointer.
void addNumber( int **array_ptr, size_t *array_size, size_t type_size, int number ) {
/* Increment the size and make sure that bubbles up */
*array_size = *array_size + 1;
/* realloc might grow the memory, or it might allocate new memory
either way, assign the result back to its original variable
by dereferencing the double pointer.
*/
*array_ptr = realloc(*array_ptr, *array_size * type_size);
/* Since it's a double pointer, we have to first dereference it before using
it as an array */
(*array_ptr)[*array_size - 1] = number;
}
(Note that I also pass in the sizeof the elements in the array, that can't be assumed).
This is called by passing a pointer to the array.
addNumber(&a, &size, sizeof(int), 5);
After that, everything is the same.
for( int i = 0; i < size; i++ ) {
printf("%d ", a[i]);
}
puts("");
Eventually you'll want to improve this by having the array, size, and type in a struct so you can pass that around in a neat package.
typedef struct {
int *array;
size_t size;
} IntArray;
This is great to do as an exercise, you'll learn a lot and kick a lot of bad habits about static memory. But doing dynamic data structures correctly and efficiently is difficult (for example, allocating one extra slot at a time is very inefficient).
There are many, many libraries out there which provide such dynamic structures. So continue with this as an exercise, but for real code use a library such as Gnome Lib.
Why? Can't get the reason.
That's because you are modifying the value of a locally in addNumber. That does not change the value of a in main.
In order for main to have access to the newly allocated memory, you need to change addNumber to return the newly allocated pointer.
int* addNumber(int* a, int* size, int number){
...
return a;
}
and then change main to:
if(!contains(a, size, 2)){
a = addNumber(a, &size, 2);
// Assign to a the new pointer value.
}
Your 'a' in main is already a pointer, passing it to a function passes a copy of it. What you have to do is - pass the adress '&a' and receive it in funtion as double pointer '**a' and inside the function, use dereference to get values inside array ( like *a[i] and free(*a).
Change the last line to 'return temp' and collect it in main as a=addnumber(&a,&size,2);
By the way, instead of going through all these hassle why don't you just use realloc() function. It increases the size of array dynamically. After using realloc you can just add the new number at the last index.

Segmentation fault (core dumped) [Conway's game of life]

I'm working on a C implementation for Conway's game of life, I have been asked to use the following header:
#ifndef game_of_life_h
#define game_of_life_h
#include <stdio.h>
#include <stdlib.h>
// a structure containing a square board for the game and its size
typedef struct gol{
int **board;
size_t size;
} gol;
// dynamically creates a struct gol of size 20 and returns a pointer to it
gol* create_default_gol();
// creates dynamically a struct gol of a specified size and returns a pointer to it.
gol* create_gol(size_t size);
// destroy gol structures
void destroy_gol(gol* g);
// the board of 'g' is set to 'b'. You do not need to check if 'b' has a proper size and values
void set_pattern(gol* g, int** b);
// using rules of the game of life, the function sets next pattern to the g->board
void next_pattern(gol* g);
/* returns sum of all the neighbours of the cell g->board[i][j]. The function is an auxiliary
function and should be used in the following function. */
int neighbour_sum(gol* g, int i, int j);
// prints the current pattern of the g-board on the screen
void print(gol* g);
#endif
I have added the comments to help out with an explanation of what each bit is.
gol.board is a 2-level integer array, containing x and y coordinates, ie board[x][y], each coordinate can either be a 1 (alive) or 0 (dead).
This was all a bit of background information, I'm trying to write my first function create_default_gol() that will return a pointer to a gol instance, with a 20x20 board.
I then attempt to go through each coordinate through the 20x20 board and set it to 0, I am getting a Segmentation fault (core dumped) when running this program.
The below code is my c file containing the core code, and the main() function:
#include "game_of_life.h"
int main()
{
// Create a 20x20 game
gol* g_temp = create_default_gol();
int x,y;
for (x = 0; x < 20; x++)
{
for (y = 0; y < 20; y++)
{
g_temp->board[x][y] = 0;
}
}
free(g_temp);
}
// return a pointer to a 20x20 game of life
gol* create_default_gol()
{
gol* g_rtn = malloc(sizeof(*g_rtn) + (sizeof(int) * 20 * 20));
return g_rtn;
}
This is the first feature I'd like to implement, being able to generate a 20x20 board with 0's (dead) state for every coordinate.
Please feel free to criticise my code, I'm looking to determine why I'm getting the segmentation fault, and if I'm allocating memory properly in the create_default_gol() function.
Thanks!
The type int **board; means that board must contain an array of pointers, each of which points to the start of each row. Your existing allocation omits this, and just allocates *g_rtn plus the ints in the board.
The canonical way to allocate your board, supposing that you must stick to the type int **board;, is:
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn->size = size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
for (int i = 0; i < size; ++i)
g_rtn->board[i] = malloc(size * sizeof **g_rtn->board);
This code involves a lot of small malloc chunks. You could condense the board rows and columns into a single allocation, but then you also need to set up pointers to the start of each row, because board must be an array of pointers to int.
Another issue with this approach is alignment. It's guaranteed that a malloc result is aligned for any type; however it is possible that int has stricter alignment requirements than int *. My following code assumes that it doesn't; if you want to be portable then you could add in some compile-time checks (or run it and see if it aborts!).
The amount of memory required is the sum of the last two mallocs:
g_rtn->board = malloc( size * size * sizeof **g_rtn->board
+ size * sizeof *g_rtn->board );
Then the first row will start after the end of the row-pointers (a cast is necessary because we are converting int ** to int *, and using void * means we don't have to repeat the word int):
g_rtn->board[0] = (void *) (g_rtn->board + size);
And the other rows each have size ints in them:
for (int i = 1; i < size; ++i)
g_rtn->board[i] = g_rtn->board[i-1] + size;
Note that this is a whole lot more complicated than just using a 1-D array and doing arithmetic for the offsets, but it was stipulated that you must have two levels of indirection to access the board.
Also this is more complicated than the "canonical" version. In this version we are trading code complexity for the benefit of having a reduced number of mallocs. If your program typically only allocates one board, or a small number of boards, then perhaps this trade-off is not worth it and the canonical version would give you fewer headaches.
Finally - it would be possible to allocate both *g_rtn and the board in the single malloc, as you attempted to do in your question. However my advice (based on experience) is that it is simpler to keep the board separate. It makes your code clearer, and your object easier to use and make changes to, if the board is a separate allocation to the game object.
create_default_gol() misses to initialise board, so applying the [] operator to it (in main() ) the program accesses "invaid" memory and with ethis provokes undefined behaviour.
Although enough memory is allocated, the code still needs to make board point to the memory by doing
gol->board = ((char*) gol) + sizeof(*gol);
Update
As pointed out by Matt McNabb's comment board points to an array of pointers to int, so initialisation is more complicate:
gol * g_rtn = malloc(sizeof(*g_rtn) + 20 * sizeof(*gol->board));
g_rtn->board = ((char*) gol) + sizeof(*gol);
for (size_t i = 0; i<20; ++i)
{
g_rtn->board[i] = malloc(20 * sizeof(*g_rtn->board[i])
}
Also the code misses to set gol's member size. From what you tell us it is not clear whether it shall hold the nuber of bytes, rows/columns or fields.
Also^2 coding "magic numbers" like 20 is bad habit.
Also^3 create_default_gol does not specify any parameters, which explictily allows any numberm and not none as you might perhaps have expected.
All in all I'd code create_default_gol() like this:
gol * create_default_gol(const size_t rows, const size_t columns)
{
size_t size_rows = rows * sizeof(*g_rtn->board));
size_t size_column = columns * sizeof(**g_rtn->board));
gol * g_rtn = malloc(sizeof(*g_rtn) + size_rows);
g_rtn->board = ((char*) gol) + sizeof(*gol);
if (NULL ! = g_rtn)
{
for (size_t i = 0; i<columns; ++i)
{
g_rtn->board[i] = malloc(size_columns); /* TODO: Add error checking here. */
}
g_rtn->size = size_rows * size_columns; /* Or what ever this attribute is meant for. */
}
return g_rtn;
}
gol* create_default_gol()
{
int **a,i;
a = (int**)malloc(20 * sizeof(int *));
for (i = 0; i < 20; i++)
a[i] = (int*)malloc(20 * sizeof(int));
gol* g_rtn = (gol*)malloc(sizeof(*g_rtn));
g_rtn->board = a;
return g_rtn;
}
int main()
{
// Create a 20x20 game
gol* g_temp = create_default_gol();
int x,y;
for (x = 0; x < 20; x++)
{
for (y = 0; y < 20; y++)
{
g_temp->board[x][y] = 10;
}
}
for(x=0;x<20;x++)
free(g_temp->board[x]);
free(g_temp->board);
free(g_temp);
}
main (void)
{
gol* gameOfLife;
gameOfLife = create_default_gol();
free(gameOfLife);
}
gol* create_default_gol()
{
int size = 20;
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn = malloc(sizeof g_rtn);
g_rtn->size = size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
int i, b;
for (i = 0; i < size; ++i){
g_rtn->board[i] = malloc(sizeof (int) * size);
for(b=0;b<size;b++){
g_rtn->board[i][b] = 0;
}
}
return g_rtn;
}
Alternatively, since you also need to add a create_gol(size_t new_size) of custom size, you could also write it as the following.
main (void)
{
gol* gameOfLife;
gameOfLife = create_default_gol();
free(gameOfLife);
}
gol* create_default_gol()
{
size_t size = 20;
return create_gol(size);
}
gol* create_gol(size_t new_size)
{
gol* g_rtn = malloc(sizeof *g_rtn);
g_rtn = malloc(sizeof g_rtn);
g_rtn->size = new_size;
g_rtn->board = malloc(size * sizeof *g_rtn->board);
int i, b;
for (i = 0; i < size; ++i){
g_rtn->board[i] = malloc(sizeof (int) * size);
for(b=0;b<size;b++){
g_rtn->board[i][b] = 0;
}
}
return g_rtn;
}
Doing this just minimizes the amount of code needed.

Resources