Printing a member of an array within a struct within a struct? - c

Here I have a struct:
typedef struct Memo
{
// dynamically allocated HugeInteger array to store our Fibonacci numbers
struct HugeInteger *F;
// the current length (i.e., capacity) of this array
int length;
} Memo;
and this is the struct HugeInteger* within the Memo struct:
typedef struct HugeInteger
{
// a dynamically allocated array to hold the digits of a huge integer
int *digits;
// the length of the array (i.e., number of digits in the huge integer)
int length;
} HugeInteger;
My question is how can I access a member of the digits array within the Hugeinteger struct within the Memo struct?
I have malloced all three like so throughout my code:
Memo *newMemo = malloc(sizeof(Memo));
newMemo->F = malloc(sizeof(HugeInteger) * INIT_MEMO_SIZE); //in this case 44
for (i = 0; i < INIT_MEMO_SIZE; i++)
{
newMemo->F[i].digits = malloc(sizeof(int*) * 1); //creating an array of size 1 to test
newMemo->F[i].digits = NULL;
newMemo->F[i].length = 0;
}
I have tried for example...
newMemo->F[i].digits[0] = 1;
...which results in a segmentation fault. How can I implement the above line of code correctly? I really feel like i'm missing something important here. Thanks.

There's a problem right here:
newMemo->F[i].digits = malloc(sizeof(int) * 1); //creating an array of size 1 to test
newMemo->F[i].digits = NULL;
(Besides the syntax error that I fixed which I assume was a copy/paste error) The second line above replaces the memory address you just allocated with NULL. So that when you do this:
newMemo->F[i].digits[0] = 1;
You're writing to a NULL address.
You want to leave out the NULL assignment.

Related

C: how to initialise a vector

I would like to initalise a vector of type
struct vector
{
size_t capacity;
size_t size;
int *data;
};
I did this but i'm not sure:
struct vector *vector_new();
{
struct vector *vect;
vect = malloc (1*sizeof(vect));
vect->capacity = 1;
vect->size = 0;
int *data;
data = malloc (1*sizeof(int));
}
I think I need to allocate 2 memory spaces, one that holds the 'struct vector' and one for the data. Should I use malloc() or calloc() ?
Moreover how could I throw an error if there is not enough memory ? Thanks
Your code should look somehow like this:
#define INITIAL_CAPACITY 10 // initial capacity, choose some appropriate value
// between 1 and N
struct vector *vector_new();
{
struct vector *vect = malloc (sizeof(struct vector));
vect->capacity = INITIAL_CAPACITY;
vect->size = 0;
vect->data = malloc(sizeof(int) * INITIAL_CAPACITY);
return vect;
}
This was the easy part, now you need to write the functions that allow to put some data into the vector, then you'll probably want to use the realloc function when the size becomes larger than the capacity.
No error checking is done in this code for brevity.
For error handling you could return NULL from the vector_new function.

Freeing up struct created with malloc who's member also had a malloc

Let's say I have a struct for implementing vectors in C like this:
struct cvector {
unsigned int size; // indicates number of element in the vector
unsigned int capacity; // indicates length of the array
int* data; // array to store the actual data
};
typedef struct cvector* cvector;
Then I create this vector like this:
cvector cvector_create() {
cvector retval = (cvector)malloc(sizeof(struct cvector));
retval->capacity = 8;
retval->size = 0;
retval->data = (int*)malloc(retval->capacity * sizeof(int));
return retval;
}
I use malloc for both allocating memory for the struct and for allocating memory for the internal int array.
For freeing up my cvector I use this:
void cvector_free(cvector vector) {
free(vector);
}
My question is, do I need to free the internal int array as well separately like this: free(vector->data) or is freeing up only the struct is enough?
Yes, you need to free also vector->data, the rule is: one call to free per each call to malloc
if you are under C99, you can use flexible array members:
struct cvector {
unsigned int size; // indicates number of element in the vector
unsigned int capacity; // indicates length of the array
int data[]; // array to store the actual data
};
Notice that int data[]; must be the last member of the struct.
Then, you reserve space in this way:
cvector cvector_create() {
cvector retval = malloc(sizeof(struct cvector) + (sizeof(int) * 8));
retval->capacity = 8;
retval->size = 0;
return retval;
}
Now, calling free(vector) is enough since vector and vector->data are on the same block.

Passing An Array of Pointers to Function

I have a struct called menu_item that looks like:
struct menu_item
{
char name[ITEM_NAME_LEN+1];
};
And in main I declare an array of pointers to the struct (am I right about this part?):
struct menu_item * menu_items[NUM_MENU_ITEMS];
And also in main I'm trying to call:
init_menu(&menu_items[NUM_MENU_ITEMS]);
init_menu function looks like this:
void menu_init(struct menu_item * menu_items[NUM_MENU_ITEMS])
{
/* allocate memory for each element in the array */
menu_items[NUM_MENU_ITEMS] = (struct menu_item *) malloc(sizeof(struct menu_item));
}
However I'm getting a segmentation error, what am I doing wrong? Thanks in advance.
Take a closer look to your function.
void menu_init(struct menu_item * menu_items[NUM_MENU_ITEMS])
{
/* allocate memory for each element in the array */
menu_items[NUM_MENU_ITEMS] = (struct menu_item *) malloc(sizeof(struct menu_item));
}
You need to carry the size of the array in a second parameter in your function. However, NUM_MENU_ITEMS, seems to be a global #define, thus you don't need to carry a second parameter.
Then you are accessing an out of bound cell, menu_items[NUM_MENU_ITEMS]. I assume you know that the indexing starts from 0 and ends at NUM_MENU_ITEMS-1.
In your function, you need, inside a loop, to allocate memory. Moreover, you don't need to cast what malloc returns.
So, for example, you could do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ITEM_NAME_LEN 15
#define NUM_MENU_ITEMS 3
// Define the struct before main
struct menu_item {
char name[ITEM_NAME_LEN + 1];
};
// Give a synonym. Now struct menu_item is the same with menu_item_t.
// Notice the _t extension, which implies that this is a typedef.
typedef struct menu_item menu_item_t;
/**
* Given a pointer 'p' to an array of pointers
* (of type menu_item_t), allocate memory for
* every cell of the array.
*/
void init_menu(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
// for every cell of our array, allocate memory
p[i] = malloc(sizeof(menu_item_t));
// check that allocation for the i-th cell is OK
if(!p[i]) {
printf("Error in allocating %d item!\n\n", i);
return;
}
}
}
/**
* Given a pointer 'p' to an array of pointers
* (of type menu_item_t), de-allocate memory for
* every cell of the array.
*/
void delete_menu(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
// free the memory we had allocated for the i-th cell
free(p[i]);
// set the pointer to NULL
p[i] = NULL;
}
}
void fill(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
strcpy(p[i]->name, "myitem");
}
}
void print(menu_item_t* p[]) {
int i;
for(i = 0; i < NUM_MENU_ITEMS; ++i) {
printf("%s\n", p[i]->name);
}
}
int main(void) {
// Declare an array of pointers of menu_items_t.
// The size of the array is NUM_MENU_ITEMS
menu_item_t *menu_items[NUM_MENU_ITEMS];
init_menu(menu_items);
fill(menu_items);
print(menu_items);
delete_menu(menu_items);
return 0;
}
When I deal with structs, I always have this example on mind.
You are calling your function as
init_menu(&menu_items[NUM_MENU_ITEMS]);
This does not make sense. Expression &menu_items[NUM_MENU_ITEMS] creates a pointer to element with index NUM_MENU_ITEMS. Such element does not exist. Your array has elements numbered from 0 to NUM_MENU_ITEMS - 1. There's no element with index NUM_MENU_ITEMS.
Expression &menu_items[NUM_MENU_ITEMS] produces a pointer into the uncharted memory past the end of the array. You pass that pointer to the function. Later you are trying to use that pointer as if it were your array. You write into that uncharted memory, which causes a crash.
If you want to pass your array to the function, just pass it. Your function should be called as
init_menu(menu_items);
That's it. There's no need to create any pointers to any elements with strange indices.
Later, inside your function you are again trying to access element NUM_MENU_ITEMS of your array
menu_items[NUM_MENU_ITEMS] = ...
This does not make sense either for the very same reasons.

Dynamically allocating 2-dimensional array in Struct (in C)

I have a structure called container that has two fields: labels and linked_to_containers; The field labels is designed to be a 2-dimensional array of int, and the field linked_to_containers is designed to be a 2-dimensional array of int pointers. On top of this, I also have an array of struct container that are dynamically created in the initiation program. I have the following code written down, but one thing I'm unsure about is the first malloc I used inside of the function container_init(). As the struct container still does not have its size initialized, is this the right way to do malloc for creating an array of struct container?
Please see my question in my comments in the code, and I will appreciate your feedback.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct container {
int *labels[2]; /* two-dimensional array of int */
int **linked_to_container[2]; /* two-dimensional array of pointers to label */
} container;
int get_next_container_index(int current_container_index, int max_index)
{
if (max_index - current_container_index >= 1)
{
return current_container_index + 1;
}
else
return 0; /* elements at two ends are linked */
}
container *allcontainers; /* an array for all containers */
void container_init(int num_containers, int column_num)
{
/* is this right to malloc memory on the array of container when the struct size is still unknown?*/
allcontainers = (container *) malloc(num_containers * sizeof(container));
int i;
for (i = 0; i < num_containers; i++)
{
container *current_container = &allcontainers[i];
current_container->labels[0] = malloc(column_num * sizeof(int));
current_container->labels[1] = malloc(column_num * sizeof(int));
current_container->linked_to_container[0] = malloc(column_num * sizeof(int *));
current_container->linked_to_container[1] = malloc(column_num * sizeof(int *));
int j;
for (j = 0; j < column_num; j++)
{
current_container->labels[0][j] = 0; /* initialize all labels to 0 */
current_container->labels[1][j] = 0;
int next_container = get_next_container_index(i, num_containers - 1); /* max index in all_containers[] is num_containers-1 */
current_container->linked_to_container[0][j] = &(allcontainers[next_container]->labels[0]);
}
}
The line in question seems perfectly fine to me, the size of struct container is well-known, because of its definition. The only size not known is the size of the arrays that the pointers in the struct will eventually point to, but that doesn't affect the size of the pointers themselves and thus also not the struct's size.
The only issue I see is here:
current_container->linked_to_container[0][j] = &(allcontainers[next_container]->labels[0]);
linked_to_container[0][j] is of type int*, but labels[0] is of type int* and therefore &(labels[0]) is of type int**. I am not sure what you try to accomplish here, but you probably need another index to labels[0][...] or & shouldn't be there.

what is causing segmentation fault in c code, dynamic allocation accross functions

I am trying to have dynamically allocate arrays of structures and perform operations on them but i keep running into segmentation faults. could someone help me out?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void *malloc(size_t size);
typedef struct {
double x;
double y;
} coords;
struct figure {
char fig_name[128];
int coordcount, size_tracker;
coords *pointer;
} fig;
void init_fig(int n, struct figure **point)
{
printf("%u\n", sizeof(coords));
point[n]->pointer = malloc(sizeof(coords) * 20); <-------SEGFAULT
if (point[n]->pointer == NULL){
exit(-1);
}
point[n]->pointer[19].x = 2;
point[n]->pointer[0].x = 1;
point[n]->pointer[0].y = 2;
point[n]->pointer[7].x = 100;
}
int main()
{
int numfigs = 1;
struct figure * point;
point = malloc(sizeof(struct figure) * 16);
point = &fig;
point[1].coordcount = 1;
init_fig(numfigs, &point);
return 0;
}
I labelled where the first seg fault occurs, (used ddd). what i dont get is that i can manipulate point[1] in main but not in any other function.
I agree with #Maxim Skurydin.
Nevertheless I'd like to explain your mistake in some more details.
Reading your init_fig one assumes that the parameter you pass struct figure **point - is actually array of pointers to struct figure. And this function accesses its n'th element.
However in your main you do something else. You allocate an array of struct figure, and your point variable points to its head. Then you take the address of this local variable and call your init_fig.
Here's the problem. init_fig assumes that you pass it an array of pointers, whereas actually this "array" consists of a single element only: the local point variable declared in main.
EDIT:
How to do this properly.
Leave main intact, fix init_fig.
This means that actually there's an array of figure structs. Means - a single memory block, interpreted as an array of consequent structs.
void init_fig(int n, struct figure *point)
{
printf("%u\n", sizeof(coords));
point[n].pointer = malloc(sizeof(coords) * 20); <-------SEGFAULT
if (point[n].pointer == NULL){
exit(-1);
}
point[n].pointer[19].x = 2;
point[n].pointer[0].x = 1;
point[n].pointer[0].y = 2;
point[n].pointer[7].x = 100;
}
Leave init_fig intact. Fix main.
This means that we actually should allocate an array of pointers, every such a pointer should point to an allocated point structure.
int main()
{
int numfigs = 1;
struct figure ** point;
point = malloc(sizeof(struct figure*) * 16);
for (i = 0; i < 16; i++)
point[i] = malloc(sizeof(struct figure));
point[1].coordcount = 1;
init_fig(numfigs, &point);
return 0;
}
You allocate memory and store the pointer in point but then you forget that pointer when you assign &fig to it.
point = malloc(sizeof(struct figure) * 16);
point = &fig;
So, you are essentially trying to write fig[1], that does not make sense.
struct figure * point;
point = malloc(sizeof(struct figure) * 16);
here point is pointer pointing to memory of 16 structures in heap
but in the next line you have done this
point = &fig;
so its memory leak and also point is not pointing to that allocated region anymore
and also init_fig should be like this
void init_fig(int n, struct figure **point)
It's the problem of segfault
Eliminate this line point = &fig;
and modify the function:
void init_fig(int n, struct figure *point)
{
...
point[n].pointer = (coords*) malloc(sizeof(coords) * 20);
...
}
since you should pass an array of structs and not an array of pointers.
Also, add a third parameter to the init_fig function so you can pass the size of the array of points that you want to create. Like :
void init_fig(int n, struct figure *point, int size)
{
...
point[n].pointer = (coords*) malloc(sizeof(coords) * size);
...
}
Therefore, making the function more reusable.
Modify also the call to that function:
init_fig(numfigs, &point); to init_fig(numfigs, point);

Resources