Initialize struct with malloc in C - c

So I have what I think is a noob question. Sorry for that in advance, and for the grammar as english is not my primary language.
So I have to make a game of checkers. I have some struct, defined by
struct game {
int **board;
int xsize, ysize;
struct move *moves;
int cur_player;
};
struct coord {
int x, y;
};
struct move_seq {
struct move_seq *next;
struct coord c_old;
struct coord c_new;
int piece_value;
struct coord piece_taken;
int old_orig;
};
struct move {
struct move *next;
struct move_seq *seq;
};
And I have to initialize a struct game wih the fonction
struct game *new_game(int xsize, int ysize)
So, here's my problem. I call, for now, new_game always with 10 and 10 values for xsize an ysize. Then I initialize the board game, which I want to assign later.
int black = 1;
int white = 5;
int **board;
int i;
int j;
int k;
for(i=0;i<xsize;i++)
{
for(j=0;j<ysize;j++)
{
if(i<(xsize/2) && j<(ysize/2) && (i+j)%2!=0)
{
board[i][j] = black;
}
else if(i>(xsize/2) && j>(ysize/2) && (i+j)%2!=0)
{
board[i][j] = white;
}
else board[i][j] = 0;
}
}
struct game *new = malloc (sizeof(struct game *));
if (new == NULL) return NULL;
So, my problem is after that. I just have Segmentation Fault whatever I do with my struct new.
I tried to do assign new->xsize = xsize and the same with ysize. I do a malloc for the board and the struct move, like I learned to do, but I kept getting this error of Segmentation Fault.
So here's my real question: How to assign and initialize correctly a struct ? Do I Have to make a malloc for each of the member of struct game ? (I tried that too but without any success...)
I don't necessarily want just the answer, I'd prefer to really understand what I have to do in this case and in general, to make less mistakes in the future.
Thanks in advance for your help.
Have a good day.

It happens because you only allocated space for a pointer to your struct. What you need to do, is allocate it for the entire size of it:
struct game *new = malloc (sizeof(struct game));
Edit: Don't be mislead by the return value of malloc, as it returns a pointer to the allocated space, that's why it should be struct game *new as it is.

In addition to Michael's bug fix, I also wonder about board: it is not allocated, yet you write to it. I think it should be like:
struct game *new_game(int xsize, int ysize)
{
int black = 1;
int white = 5;
int i;
int j;
struct game *new = malloc (sizeof(struct game));
if (new == NULL) return NULL;
game->xsize= xsize;
game->ysize= ysize;
game->board= malloc(xsize*ysize*sizeof(int));
for(i=0;i<xsize;i++)
{
for(j=0;j<ysize;j++)
{
if(i<(xsize/2) && j<(ysize/2) && (i+j)%2!=0)
{
game->board[i*xsize+j] = black;
}
else if(i>(xsize/2) && j>(ysize/2) && (i+j)%2!=0)
{
game->board[i*xsize+j] = white;
}
else game->board[i*xsize+j] = 0;
}
}
return (game);
}
Note also the array indexing: the compiler doesn't know the dynamic rowsize so you have to do that yourself.

Related

Dynamic allocation of union of structs

I am trying to create a union of 2 structs (dfp and affine) and want to allocate them dynamically. I am getting errors in creating particular struct array inside union. Am I declaring union in right way?
#include <stdio.h>
#include <stdlib.h>
struct{
int fp;
}dfp;
struct{
int scale;
int zp;
}affine;
union{
struct dfp *df;
struct affine *af;
}quant;
struct member{
int total;
union quant arr;
};
int main(void) {
// your code goes here
struct member* ptr;
ptr = (struct member *)malloc(sizeof(struct member));
ptr->total = 2;
int type = 0;
if(!type){
ptr->arr->df = (struct dfp*)malloc(ptr->total*sizeof(struct dfp)); //error
for(int i=0;i<2;i++){
ptr->arr->df->fp[i] = 10;
}
}
else{
ptr->arr->af = (struct affine*)malloc(ptr->total*sizeof(struct affine)); //error
for(int i=0;i<2;i++){
ptr->arr->af->scale[i] = 10;
ptr->arr->af->zp[i] = 20;
}
}
return 0;
}
Most issues have already been pointed out by others separately. This is my attempt at writing a complete answer with explanations and advice.
First off, please check your exact compiler warnings and errors. These are your best help in resolving these kind of issues.
The program does not contain a union of structs, but a union of pointers to structs.
The program's definitions are not correct. Taking dfp as an example. This, struct { int fp; } dfp;, defines an anonymous struct with the the variable name dfp. The name of the struct should go before the struct declaration list, e.g. struct dfp { int fp; };. See here or see the C standard specifications.
Judging by the code in main, the member variables of the structs should be arrays of size 2 instead of single ints.
The operator -> is for "member access using a pointer". Since arr is not a pointer, use a dot (.) to access its members. See here.
Dynamically allocated memory must be free'd, or else the program will have one or more memory leaks.
Here is the full code with all mentioned corrections:
#include <stdio.h>
#include <stdlib.h>
struct dfp {
int fp[2];
};
struct affine {
int scale[2];
int zp[2];
};
union quant {
struct dfp *df;
struct affine *af;
};
struct member {
int total;
union quant arr;
};
int main(void) {
struct member* ptr;
ptr = (struct member *)malloc(sizeof(struct member));
ptr->total = 2;
int type = 0;
if(!type) {
ptr->arr.df = (struct dfp*)malloc(ptr->total*sizeof(struct dfp));
for(int i=0;i<2;i++){
ptr->arr.df->fp[i] = 10;
}
}
else {
ptr->arr.af = (struct affine*)malloc(ptr->total*sizeof(struct affine));
for(int i=0;i<2;i++){
ptr->arr.af->scale[i] = 10;
ptr->arr.af->zp[i] = 20;
}
}
if(!type) {
free(ptr->arr.df);
}
else {
free(ptr->arr.af);
}
free(ptr);
}
Correct the struct definition as below:
struct dfp {
int fp;
};
struct affine{
int scale;
int zp;
};

Understanding Malloc and Realloc in regards to an array of structs

I have been struggling with the ideas behind malloc and realloc for quite some time now and at the moment I have a problem with dynamically creating an array of structs. I have a struct triangle which itself is composed of an array of struct coordinates. I would like to be able to have an array of triangles which is as large as necessary, but every time I attempt to increase the length of my array, nothing seems to happen. Realloc doesn't fail and neither does malloc. However the new triangles are not inserted in my array. Here is my code for reference.
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
struct coordinate {
int x;
int y;
};
struct triangle {
struct coordinate point[3];
};
static size_t size = 0;
static void addTriangle(struct triangle **triangles, struct triangle *t) {
struct triangle *ts = (struct triangle*) realloc(*triangles, (size+1) * sizeof(struct triangle));
if(ts == NULL) {
free(ts);
exit(EXIT_FAILURE);
}
*triangles = ts;
triangles[size] = t;
size++;
}
int main() {
struct triangle* triangles = (struct triangle *) malloc(sizeof(struct triangle));
if(triangles == NULL) {
free(triangles);
exit(EXIT_FAILURE);
}
for(int i = 0; i < 2; i++) {
struct coordinate *a = malloc(sizeof(struct coordinate));
a->x = 1 * i;
a->y = 2 * i;
struct coordinate *b = malloc(sizeof(struct coordinate));
b->x = 3 * i;
b->y = 4 * i;
struct coordinate *c = malloc(sizeof(struct coordinate));
c->x = 5 * i;
c->y = 6 * i;
struct triangle *t = malloc(sizeof(struct triangle));
t->point[0] = *a;
t->point[1] = *b;
t->point[2] = *c;
addTriangle(triangles, t);
}
}
I have tried every variation of this I have found, but I would rather not just blindly throw in & and * until something happens.
As-is, your program invokes undefined behavior when it passes an uninitialized *triangles to realloc: https://taas.trust-in-soft.com/tsnippet/t/9ff94de4 . You probably meant to pass &triangles when you called it in main.
Changing the call in main to addTriangle(&triangles, t);, the next issue is an out-of-bounds access inside addTriangle: https://taas.trust-in-soft.com/tsnippet/t/658228a1 . Again this may be because you have the wrong level of indirection and meant something like (*triangles)[size]
instead of triangles[size].
If I change the line triangles[size] = t; to (*triangles)[size] = *t; then there is no undefined behavior. You should check whether this program still does what you want, since it was modified: https://taas.trust-in-soft.com/tsnippet/t/8915bd2d
The final version:
#include <string.h>
#include <stdlib.h>
struct coordinate {
int x;
int y;
};
struct triangle {
struct coordinate point[3];
};
static size_t size = 0;
static void addTriangle(struct triangle **triangles, struct triangle *t) {
struct triangle *ts = (struct triangle*) realloc(*triangles, (size+1) * sizeof(struct triangle));
if(ts == NULL) {
free(ts);
exit(EXIT_FAILURE);
}
*triangles = ts;
(*triangles)[size] = *t; // a struct assignment
size++;
}
int main() {
struct triangle* triangles = (struct triangle *) malloc(sizeof(struct triangle));
if(triangles == NULL) {
free(triangles);
exit(EXIT_FAILURE);
}
for(int i = 0; i < 2; i++) {
struct coordinate *a = malloc(sizeof(struct coordinate));
a->x = 1 * i;
a->y = 2 * i;
struct coordinate *b = malloc(sizeof(struct coordinate));
b->x = 3 * i;
b->y = 4 * i;
struct coordinate *c = malloc(sizeof(struct coordinate));
c->x = 5 * i;
c->y = 6 * i;
struct triangle *t = malloc(sizeof(struct triangle));
t->point[0] = *a;
t->point[1] = *b;
t->point[2] = *c;
addTriangle(&triangles, t); /* pass the address of triangles
so that addTriangle can modify this variable's contents */
}
}
Side remarks not directly related to the problem you asked about
As long as you program in C, please do not cast the result of malloc. Simply write struct triangle* triangles = malloc(....
As noted by #aschepler in the comments, this program still leaks the memory blocks allocated from main. These can be freed at the end of each iteration without adding any undefined behavior: https://taas.trust-in-soft.com/tsnippet/t/a0705262 . Doing this, you may realize that t->point[0] = *a;, ... are in fact struct assignments and that it was unnecessary to allocate a separate struct coordinate in the first place: you could just fill in each struct coordinate member of the struct triangle. In addition, it was unnecessary to allocate the struct triangle in main, too: you could just use a local variable for that, since anyway the contents of the struct will be copied by the function addTriangle to the array that main's local variable triangles points to.
Also you don't need to call free(triangles) if triangles is a null pointer in main:
struct triangle* triangles = (struct triangle *) malloc(...
if(triangles == NULL) {
free(triangles);
exit(EXIT_FAILURE);
}
It is allowed to pass a null pointer to free, and this does what you would expect (it does nothing), but since you know that triangles is NULL in the then branch, simply call exit.
Handling the failure of realloc on the other hand is a subtle subject. Your program is doing it wrong, but it does not really matter because it calls exit immediately.
Storing information about the allocated array pointed by main's local variable triangles in a static file-scope variable size is not consistent. The two are so closely related that they should be in the same scope. Since you need addTriangle to be able to change size, you cannot simply move size to be a local variable of main, but you can move the local variable triangles of main to file scope, next to size. If you prefer to make size a local variable of main after all, you will need to pass its address to the function addTriangle so that the latter can update the former.
Change the function call as
addTriangle(&triangles, t);
You can replace the whole body of your for loop with
struct triangle t = {{{i, 2*i},{3*i,4*i},{5*i,6*i}}};
addTriangle(&triangles, &t);
Please note the & before the parameters, because you want to pass the address of both.
I already noticed as a comment that triangles[size] = t; should be (*triangles)[size] = *t;
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
struct coordinate {
int x;
int y;
};
struct triangle {
struct coordinate point[3];
};
static size_t size = 0;
static void addTriangle(struct triangle **triangles, struct triangle *t) {
struct triangle *ts = realloc(*triangles, (size+1) * sizeof(struct triangle));
if(ts == NULL) {
exit(EXIT_FAILURE);
}
*triangles = ts;
(*triangles)[size] = *t;
size++;
}
int main() {
struct triangle* triangles = malloc(sizeof(struct triangle));
if(triangles == NULL) {
exit(EXIT_FAILURE);
}
for(int i = 0; i < 2; i++) {
struct triangle t = {{{i, 2*i},{3*i,4*i},{5*i,6*i}}};
addTriangle(&triangles, &t);
}
for(int i = 0; i < size; i++) {
printf("%d %d, %d %d, %d %d\n", triangles[i].point[0].x,
triangles[i].point[0].y,
triangles[i].point[1].x,
triangles[i].point[1].y,
triangles[i].point[2].x,
triangles[i].point[2].y);
}
}

Segmentation fault in assigning value to a dynamic array of Nodes, inside a structure

I am trying to create a Hash Map in C. Below is the code. When I try to
assign value to the elements of Darray ( each of which is a pointer to a Node) I am getting a segmentation fault ( i.e. at line 23 and24). Could anybody help in pointing out where am I going wrong.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
typedef struct Map{
struct Node** Darray;
} Map;
#define SIZE 10
int main()
{
int i=0;
Map* M = malloc(sizeof(Map));
M->Darray = (struct Node**)malloc(sizeof(Node*)*SIZE);
for (i =0;i < SIZE;i++){
M->Darray[i]->data =0;
M->Darray[i]->next =NULL;
}
}
You allocate space for SIZE pointers to Node, but don't initialize these in any way, so when you access M->Darray[i] in M->Darray[i]->data you get segmentation fault because value of M->Darray[i] has not been set.
You need to allocate space for each node before using it:
for (i = 0; i < SIZE; i++) {
M->Darray[i] = malloc(sizeof(Node));
M->Darray[i]->data = 0;
M->Darray[i]->next = NULL;
}
Depending on your needs, you could also change Darray to be an array of nodes instead of node pointers, so you can allocate space for all nodes at once:
struct Node* Darray;
...
M->Darray = malloc(sizeof(Node) * SIZE);
for (i = 0; i < SIZE; i++) {
M->Darray[i].data = 0;
M->Darray[i].next = NULL;
}

Can't pass/return a struct pointer successfully

I'm trying to pass a pointer to a struct to a function and then return an edited version of said pointer.
These are the declarations of the structs:
struct HshTble;
typedef struct HshTble *HashTable;
enum EntryStatus { Occupied, Empty, Deleted };
struct HashEntry {
int Element;
enum EntryStatus Info;
};
typedef struct HashEntry Entry;
struct HshTble{
int TableSize;
Entry *Array;
};
So as you can see there is a pointer to a struct within the other struct.
My issue is when it comes to trying to do something with these things... I'll put my code so far, hopefully it's clear what's supposed to be happening but I'll add notes too.
void main(){
HashTable *table;
int size;
table = (HashTable*) malloc (sizeof(HashTable));
table = createTable(table, &size);
In this next bit is where the issues have risen, the idea is I want to edit the values inside table:
HashTable createTable(HashTable table, int *size){
int x, y, ch;
*size = 0;
fopen_s(&fp, DATA_FILENAME, "r");
while (EOF != fscanf_s(fp, DATA_FILENAME, &ch))
{
y = x = f(ch);
++*size;
if (table->Array[x].Info != Occupied)
{
table->Array[x].Element = ch;
table->Array[x].Info = Occupied;
}
else if (table->Array[x].Info == Occupied)
{
while (table->Array[y].Info == Occupied)
{
if (y > HASH_TABLE_SIZE)
{
y = 0;
table->Array[y].Element = ch;
table->Array[y].Info = Occupied;
}
else
{
table->Array[y + 1].Element = ch;
table->Array[y + 1].Info = Occupied;
}
y++;
}
}
return table;
}
}
It doesn't seem to like my function have the type of one of my structures among other things but I feel this is my main issue at the moment. Any help would be great.
Try
void createTable(HashTable &table, int *size){
Just modify the object passed as a parameter. You don't need a return then.
For C do
void createTable(HashTable *table, int *size){

How to malloc "MyDef ** t" to a specific length, instead of "MyDef * t[5]" in C

A struct like the following works fine, I can use t after calling malloc(sizeof(mystruct)):
struct mystruct {
MyDef *t[5];
};
I want to be able to dynamically set the length of the array of MyDef, like the following:
struct mystruct {
MyDef **t;
int size;
};
What do I need to do additionally to malloc(sizeof(mystruct)) to get this to work, so I can do TestStruct->t[3] = something? Just getting a segmentation fault!
Thanks!
EDIT with code that causes seg fault, unless I'm blind this seems to be what the answers are so far:
#include <stdio.h>
typedef struct mydef {
int t;
int y;
int k;
} MyDef;
typedef struct mystruct {
MyDef **t;
int size;
} MyStruct;
int main(){
MyStruct *m;
if (m = (MyStruct *)malloc(sizeof(MyStruct)) == NULL)
return 0;
m->size = 11; //seg fault
if (m->t = malloc(m->size * sizeof(*m->t)) == NULL)
return 0;
return 0;
}
struct mystruct *s = malloc(sizeof(*s));
s->size = 5;
s->t = malloc(sizeof(*s->t) * s->size);
m = (MyStruct*)malloc(sizeof(MyStruct)) == NULL
What that does. Calls malloc, compares return of malloc to NULL. Then assigns the result of that comparison(a boolean value) to m.
The reason it does that is because '==' has a higher precedence than '='.
What you want:
if ( (m = (MyStruct *)malloc(sizeof(MyStruct))) == NULL)
...
if ( (m->t = malloc(m->size * sizeof(*m->t))) == NULL)
That happens because you do not allocate memory for array itself, only for pointer to this array.
So, first you have to allocate mystruct:
struct_instance = malloc(sizeof(mystruct));
and then you have to allocate memory for array of pointers to MyDef and initialize pointer in your struct
struct_instance->size = 123;
struct_instance->t = malloc(sizeof(MyDef*) * struct_instance->size);

Resources