Why is it so important to create space with malloc for structs so the struct will be on the heap. Why cant the struct be created without malloc and stay on the stack ? We are being thought this concept in school, but i dont understand why.
// A simple C program for traversal of a linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// This function prints contents of linked list starting from
// the given node
void printList(struct Node* n)
{
while (n != NULL) {
printf(" %d ", n->data);
n = n->next;
}
}
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
second->data = 2; // assign data to second node
second->next = third;
third->data = 3; // assign data to third node
third->next = NULL;
printList(head);
return 0;
}
I just defined a new struct type typedef struct graph_struct {} struct; and I need to make one of them in my main function. There are two options for a constructor:
-
Declare a
graphinmain(), and pass its address to the constructor. Return nothing. -
Pass nothing to the constructor,
mallocagraphinside of it, and return a pointer to thegraph.
I prefer 2), but I think that memory on the heap is slower to work with than memory on the stack. And my program does need to be really fast.
Is there any reason to prefer one over the other?
Videos
In this function,
void
allocateMem(struct myStruct *struct1)
{
struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
}
struct1 is passed by value. Any changes you make to it in the function are not visible from the calling function.
A better alternative:
struct myStruct* allocateMem()
{
struct myStruct *struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
return struct1;
}
Change the calling function to:
int
main(int argc, char *argv[])
{
struct myStruct *struct1 = allocateMem();
printf("number: %d\n", struct1->number);
// Make sure to free the memory.
free(struct1);
return 0;
}
A pointer is just an integer in reality, when you pass in struct1 to your function since struct1 is null you are just passing in a 0 to your function in reality. that value gets passed on the stack and you do a heap allocation and update the stack value with the new address. but when you return from the function, that value just gets popped of the stack and you have leaked that memory. the value of struct1 in main (which is also on the stack still keeps its value 0(NULL). so you have to pass in a pointer to your pointer if you want to update that value, or what might be easier is just to return the malloc'd pointer from your function.
This is one way you could modify your function to work:
#include <stdio.h>
#include <stdlib.h>
struct myStruct
{
int number;
};
struct myStruct*
allocateMem()
{
struct myStruct* struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
return struct1;
}
int
main(int argc, char *argv[])
{
struct myStruct *struct1 = allocateMem();
printf("number: %d\n", struct1->number);
return 0;
}
Hey friends,
I'm sure somebody on the internet jas alread answered this, but I honestly haven't found a suitable answer for me.
Let's say we have a struct like this:
typedef struct {
char *name;
int age;
} Human;And a kind of "constructor" function like this:
Human *human_new(char *name, int age)
{
Human *this = (Human *) malloc(sizeof(Human));
this->name = name;
this->age = age;
return this;
}
My question is, do I need to allocate memory for the char pointer name of the struct or is the assignment of this->name enough?
Hi,
currently I'm train my C skills (or get some in general, lol) and make a little training project: classical tic tac toe. I will "overcomplicate" the project on purpose with the intention to use many language skills as possible.
I will represent the "board" with this two structures:
struct game_board_bitmap {
char player: 2;
};
struct game_board {
unsigned int width;
unsigned int height;
unsigned int size;
struct game_board_bitmap* fields[];
};A classic board has a width and height of 3, so a size of 9. Every field should be represented with the struct game_board_bitmap and saved in a variable array in the struct game_board.
The purpose of the shown structure is to train the correct handling of malloc, free etc.
And this is also where I reach my limits. How do I create this nested structure correctly? I have tried it via the following way:
struct game_board* tictactoe_init_game_board(unsigned int const width, unsigned int const height) {
struct game_board* board = malloc(sizeof(struct game_board) + (width * height) * sizeof(struct game_board_bitmap));
// malloc test removed for space savings
board->width = width;
board->height = height;
board->size = width * height;
for (int i = 0; i < board->size; i++) {
board->fields[i]->player = 0; // 0 is default, field not assigned to any player
}
return board;
}
If I want access the board via printf("%c", board->fields[2]->player); the program crashes with a SIGSEGV. So I think I have done something wrong.
Can someone please explain to me what exactly I am doing wrong or how to do it right? Thank you! :)
EDIT: Added clarifications
I was wondering what the best practice for struct management is? I assume it will depend on the situation, but I have been doing it 2 different ways and was wondering if there are more, and if any is better than the other.
Assuming I have a struct person and a list of people struct person_list, I used to always allocate each struct with malloc, and keep track of the pointer in the list. But recently I have been experimenting with having the list keep an array of struct person (which can be dynamically increased with realloc) and copying structs into the array either using memcpy or dereference. When an person struct is needed, I return the pointer from the list. The list itself is usually malloced, so technically the structs are still on the heap.
The main reason for the last approach is the reduced memory management of each struct, and the fact I could create struct with designated initialisers.
/* list_add_person will copy the person struct, so stack allocated is fine. */
list_add_person(&list, &(struct person){
.age = 24,
.id = 1,
...
};In my C program, I have a function that looks like this:
GameState cc_newGame(void) {
// Create a new game state
GameState* game = (GameState*)NULL;
// Set the fields to their default values
game->tick = 0;
return *game;
}Will creating a struct this way cause issues in my program?
EDIT: Thanks to a comment by u/whyeventrymore, I was able to figure out how to do this using malloc.
Hey I'm fairly new to C, and just trying to wrap my head around the memory portion of having an array of structs which themselves contain character arrays. Here's some simple test code, could anyone tell me if I'm doing this right?
#include <stdio.h>
#include <stdlib.h>
int main() {
typedef struct {
char *name;
} Student;
//allocate memory
int totalElements = 3;
Student *myArray = (Student*)malloc(totalElements * sizeof(Student));
for (int i=0; i<totalElements; i++){myArray[i].name = malloc(3);}
//set values
myArray[0].name = "Joe";
myArray[1].name = "Bob";
myArray[2].name = "Kim";
//print values
for (int i=0; i<totalElements; i++){printf("%s\n", myArray[i].name);}
//deallocate memory
for (int i=0; i<totalElements; i++){free(myArray[i].name);}
free(myArray);
return 0;
}Hello,
I've come across these different ways to build an struct. What are the differences between them? Specially the 1 and 3. I guess in the second approach the struct lives in the stack and when built with malloc it goes to the heap, but I don't understand third.
typedef struct {
uint32_t a;
uint8_t *b;
uint32_t c;
} struct_a;
typedef struct {
uint32_t aa;
struct_a *bb;
} struct_b;
int main()
{
// 1
struct_b *b1 = malloc(sizeof(struct_b));
// 2
struct_b b2;
// 3
struct_b b3 = {0};
memset(b3.bb, 0, sizeof(b3.bb));
return 0;
}
What's a nice way to insert elements into a heap allocated array in C? I want to do something like foo = { ... }; like I can for stack allocated elements, but I think that only works for the stack. I am trying foo[0] = ..; foo[1] = ...; but that causes code size explosion.
I have to heap allocate it since the array is large.
Context - this is part of my generated code, so doing both is equally easy, but the latter causes gcc to crash because of the large number of lines in the file.
#include <stdio.h>#include <string.h>#include <stdlib.h>
char *moveFromHeap(char *oldValue) {int n = strlen(oldValue) + 1;char buf[n];strncpy(buf, oldValue, n);free(oldValue);char* newreturn = buf;return newreturn;}
int main(void) {char *randomString = strdup("COPY THIS STRING!");char *k = moveFromHeap(randomString);printf("k is %s\n", k);return 0;}
I found having to free all the memory at pretty annoying, so I thought of making a function that does it for me.
This works, but I heard this is invalid. I understand this is copying from a local space, and it can cause an undefined behaviour.
-
Should I keep trying this or is this something that is not possible?
-
Does this apply for all pointers? Does any function that defines a local variable, and return a pointer pointing to the variable an invalid function, unless its written on heap space?
The same way you declare any variable on the stack:
struct my_struct {...};
int main(int argc, char **argv)
{
struct my_struct my_variable; // Declare struct on stack
.
.
.
}
To declare a struct on the stack simply declare it as a normal / non-pointer value
typedef struct {
int field1;
int field2;
} C;
void foo() {
C local;
local.field1 = 42;
}
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} *administrator;
This isn't just a struct declaration, it's also a variable declaration... it's the same as:
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
};
struct USER *administrator;
So, when you subsequently use sizeof(administrator), you'll get "the size of a pointer"... which is most likely not what you want.
You probably wanted to do something more like this:
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
};
int main(void) {
struct USER *administrator;
administrator = malloc(sizeof(*administrator));
/* - or - */
administrator = malloc(sizeof(struct USER));
/* check that some memory was actually allocated */
if (administrator == NULL) {
fprintf(stderr, "Error: malloc() returned NULL...\n");
return 1;
}
/* ... */
/* don't forget to free! */
free(administrator)
return 0;
}
sizeof(*administrator) and sizeof(struct USER) will both give you "the size of the USER structure", and thus, the result of malloc() will be a pointer to enough memory to hold the structure's data.
struct USER{
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} *administrator;
This defines administrator as a pointer variable. But, from the other code
administrator *newStruct = (administor*)malloc(sizeof(administrator));
It seems you want to use that as a type. To do so, you can make use of the typedef.
typedef struct USER{
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} administrator;
and then use
administrator *newStruct = (administrator *)malloc(sizeof(administrator));
In this case, however, is it possible to create a new instance of this struct on the heap, or would I need to define a constructor? Is there a way to create things on the heap without the new operator?
As answered before, you can create a new instance on the heap either via new or with malloc.
Or, better yet: is it unnecessary for me to cling so tightly to the notion that I shouldn't define member functions for structs?
This is the more interesting question. The major (only?) difference between struct and class in c++ is the
default access specifier. That is, struct defaults to public access and class defaults to private. In my opinion, this is the difference that should determine which of the two you use. Basically, if users should access the members directly, then it should be a struct.
If, for example, you have no member functions, then obviously the intention is for the object's members to be accessed directly and so it would be a struct. In the case of an object that is just a small private helper for the implementation of its outer class, as in your example, then even if it has member functions it is often clearest to allow the outer class access to its members and so it should be a struct. Often with these classes the implementation of the outer class is tightly coupled to the implementation of the inner class and so there is no reason to hide the one from the other.
So, for trivial (e.g. std::pair) objects or those whose use is limited (as in a private inner class) default access to members can be a good thing, and in these cases I would make them structs.
Even if you don't define a constructor, the compiler will create a default one and so you can use operator 'new':
Node *n = new Node;
AFAIAC, a struct is a class, except that its "publicness" default is reversed.