I'm tasked to create a program which dynamically allocates memory for a structure.
normally we would use
x=malloc(sizeof(int)*y);
However, what do I use for a structure variable?
I don't think its possible to do
struct st x = malloc(sizeof(struct));
Could someone help me out?
Thanks!
My favorite:
#include <stdlib.h>
struct st *x = malloc(sizeof *x);
Note that:
x must be a pointer
no cast is required
include appropriate header
You're not quite doing that right. struct st x is a structure, not a pointer. It's fine if you want to allocate one on the stack. For allocating on the heap, struct st * x = malloc(sizeof(struct st));.
struct st* x = malloc( sizeof( struct st ));
It's exactly possible to do that - and is the correct way
Assuming you meant to type
struct st *x = malloc(sizeof(struct st));
ps. You have to do sizeof(struct) even when you know the size of all the contents because the compiler may pad out the struct so that memebers are aligned.
struct tm {
int x;
char y;
}
might have a different size to
struct tm {
char y;
int x;
}
This should do:
struct st *x = malloc(sizeof *x);
struct st *x = (struct st *)malloc(sizeof(struct st));
I believe, when you call sizeof on a struct type, C recursively calls sizeof on the fields of the struct. So, struct st *x = malloc(sizeof(struct st)); only really works if struct st has a fixed size. This is only significant if you have something like a variable sized string in your struct and you DON'T want to give it the max length each time.
In general,
struct st *x = malloc(sizeof(struct st));
works. Occasionally, you will run into either variable sized structs or 'abstract' structs (think: abstract class from Java) and the compiler will tell you that it cannot determine the size of struct st. In these cases, Either you will have to calculate the size by hand and call malloc with a number, or you will find a function which returns a fully implemented and malloc'd version of the struct that you want.
Related
Has this code undefined behaviour which means for s is mandatory to allocate memory or is ok this way ?
PS: what is the difference between
struct X* x = (struct X*)malloc(sizeof(struct X));
and
struct X* x = (struct X*)malloc(sizeof(x));
and
struct X* x = (struct X*)malloc(sizeof *x);
Thank you.
#include <stdio.h>
#include <stdlib.h>
struct X
{
int x;
char* s;
};
int main()
{
struct X* x = (struct X*)malloc(sizeof(struct X));
x->x = 10;
// x->s = (char*)malloc(10);
// memcpy...
x->s = "something";
printf("is ok?");
return 0;
}
Rather than throw my own interpretation at you i felt it would be more helpful to share a link that might clarify what you are aiming to achieve:
https://www.geeksforgeeks.org/new-vs-malloc-and-free-vs-delete-in-c/
When you create a pointer i see that you have added the pointer to your char* variable / struct, but when calling them the use of the ampersand & is used as a reference to the address in the memory.
But not applied quite right using the int variable when declaring it no '*' and then referencing the location using '&'.
This is fine. Since s is part of the struct, allocating memory for the struct allocates memory for s. I would strongly suggest changing the type of s to be a const pointer, since it points to a literal which, because it's a type of constant, cannot be modified.
You cannot do s[0]='n'; after this. You did not allocate any space to hold any string other than the unmodifiable literal "something".
I am offsetting my pointer as shown in the below code to copy to another structure.
#include <stdio.h>
struct a
{
int i;
};
struct test
{
struct a *p;
int x,y,z;
};
int main()
{
struct test *ptr = malloc(sizeof(struct test));
struct test *q = malloc(sizeof(struct test));
ptr->x = 10;
ptr->y = 20;
ptr->z = 30;
memcpy(&(q->x),&(ptr->x),sizeof(struct test)-sizeof(struct a*));
printf("%d %d %d\n",q->x,q->y,q->z);
return 0;
}
Is there a better way to do my memcpy() ?
My question is what if I am in-cognizant of the members of the structure and want to just move my pointer by sizeof(struct a*) and copy rest of the structure?
Edits:
I want to copy some part of the structure but I don't know the members in it, but I know I want to skip some type of variable as shown in the example (struct a*) and copy rest of the structure.
Use offsetof(struct test, x) (C99, gcc), not sizeof(stuct a *). They are not guaranteed equal, because of padding/alignment. Caution: As a result of padding, using sizeof(..) can result in undefined behaviour, as there are copied too many chars.
offsetof(<type>, <member>) returns the offset of from the start of . So, sizef(struct test) - offsetof(struct test, x) yields the number of chars to copy all fields, starting with x.
Just read here for more details
I think the best way would be to use offsetof
memcpy(&(q->x),&(ptr->x),sizeof(struct test)-offsetof(struct test, x));
Because if first element was a little different, you could have alignment problems, whereas offsetof takes care of alignment for you.
Of course, alignement problems on a pointer should not occur on common architecture, but I think that offsetof is better practice anyway
Imagine I've the following struct
struct Memory {
int type;
int prot;
};
typedef struct Memory *Memory;
How would I initialise it using malloc()?
Memory mem = malloc(sizeof(Memory));
or
Memory mem = malloc(sizeof(struct Memory));
What is the correct way to allocate that?
Your struct declaration is a bit muddled up, and the typedef is wrong on many levels. Here's what I'd suggest:
//typedef + decl in one
typedef struct _memory {
int type;
int prot;
} Memory;
Then allocate like so:
Memory *mem = malloc(sizeof *mem);
Read the malloc call like so: "Allocate the amount of memory required to store whatever type mem is pointing to". If you change Memory *mem to Memory **mem, it'll allocate 4 or 8 bytes (depending on the platform), as it now stands it'll probably allocate 8 bytes, depending on the size of int and how the compiler pads the struct check wiki for more details and examples.
Using sizeof *<the-pointer> is generally considered to be the better way of allocating memory, but if you want, you can write:
Memory *mem = malloc(sizeof(Memory));
Memory *mem = malloc(sizeof(struct _memory));
They all do the same thing. Mind you, if you typedef a struct, that's probably because you want to abstract the inner workings of something, and want to write an API of sorts. In that case, you should discourage the use of struct _memory as much as possible, in favour of Memory or *<the-pointer> anyway
If you want to typedef a pointer, then you can write this:
typedef struct _memory {
int type;
int prot;
} *Memory_p;
In which case this:
Memory_p mem = malloc(sizeof *mem);
might seem counter intuitive, but is correct, as is:
Memory_p mem = malloc(sizeof(struct _memory));
But this:
Memory_p mem = malloc(sizeof(Memory_p));
is wrong (it won't allocate the memory required for the struct, but memory to store a pointer to it).
It's a matter of personal preference, perhaps, but I personally find typedefs obscure certain things. In many cases this is for the better (ie FILE*), but once an API starts hiding the fact you're working with pointers, I start to worry a bit. It tends to make code harder to read, debug and document...
Just think about it like this:
int *pointer, stack;
The * operator modifies a variable of a given type, a pointer typedef does both. That's just my opinion, I'm sure there are many programmers that are far more skilled than me who do use pointer typedefs.
Most of the time, though, a pointer typedef is accompanied by custom allocator functions or macro's, so you don't have to write odd-looking statements like Memory_p mem = malloc(sizeof *mem);, but instead you can write ALLOC_MEM_P(mem, 1); which could be defined as:
#define ALLOC_MEM_P(var_name, count) Memory_p var_name = malloc(count * sizeof *var_name)
or something
Both
typedef struct Memory * Memory;
and
Memory mem = malloc (sizeof (Memory));
are wrong. The correct way to do it is :
typedef struct memory
{
int type;
int prot;
} *MEMPTR;
or
struct memory
{
int type;
int prot;
};
typedef struct memory *MEMPTR;
The name of the structure should be different than the name of a pointer to it.
This construction
struct {
int type;
int prot;
} Memory;
defines an object with name Memory that has type of unnamed structure.
Thus the next construction
typedef struct Memory *Memory;
defined 1) a new type struct Memory that has nothing common with the definition above and the name Memory. and 2) another new type name Memory that is pointer to struct Memory.
If the both constructions are present in the same compilation unit then the compiler will issue an error because name Memory (the name of the pointer) in the typedef declaration tries to redeclare the object of the type of the unnamed structure with the same name Memory.
I think you mean the following
typedef struct Memory {
int type;
int prot;
} Memory;
In this case you may use the both records of using malloc like
Memory *mem = malloc( sizeof( Memory ) );
and
struct Memory *mem = malloc( sizeof( struct Memory ) );
or
Memory *mem = malloc( sizeof( struct Memory ) );
or
struct Memory *mem = malloc( sizeof( Memory ) );
because now the two identifiers Memory are in two different name spaces, The first one is used with tag struct and the second is used without tag struct.
Is this the correct way to allocate memory for a c struct that contains a dynamic array? In particular, is the way I allocate memory for myStruct correct, considering that it is not yet known how big the struct actually is?
//test.h
struct Test;
struct Test * testCreate();
void testDestroy(struct Test *);
void testSet(struct Test *, int);
//test.c
#include <stdlib.h>
struct Test{
double *var;
};
struct Test * testCreate(int size){
struct Test *myTest = (struct Test *) malloc(sizeof(struct Test));
myTest->var = malloc(sizeof(double)*size);
return(myTest);
}
void testDestroy(struct Test * myTest){
free(myTest->var);
free(myTest);
}
void testSet(struct Test * myTest, int size){
int i;
for (i=0;i<size;++i){
myTest->var[i] = i;
}
}
structs have fixed size, and that's what sizeof returns.
Your struct has on element, a double pointer, and that has a (platform dependent) fixed size.
Your testCreate function does things correctly. In case you don't know the size of the dynamically allocated part, you can set the pointer to NULL to denote that the memory has to be allocated later.
Yes, you correctly malloc space for the struct and then space for the array of doubles in the struct. As a practical matter, you should always test the return from malloc() for NULL before attempting to use the memory. Also, most programs like this store the size of the array in the struct as well so you can write more general code that ensures it doesn't run off the end of the allocated space.
#include <stdlib.h>
struct timer_list
{
};
int main(int argc, char *argv[])
{
struct foo *t = (struct foo*) malloc(sizeof(struct timer_list));
free(t);
return 0;
}
Why the above segment of code compiles (in gcc) and works without problem while I have not defined the foo struct?
because in your code snippet above, the compiler doesn't need to know the size of struct foo, just the size of a pointer to struct foo, which is independent of the actual definition of the structure.
Now, if you had written:
struct foo *t = malloc(sizeof(struct foo));
That would be a different story, since now the compiler needs to know how much memory to allocate.
Additionally, if you at an point you try to access a member of a struct foo* (or dereference a pointer to a foo):
((struct foo*)t)->x = 3;
The compiler would also complain, since at this point it needs to know the offset into the structure of x.
As an aside, this property is useful to implement an Opaque Pointer.
"And what about free(t)? Can the compiler free the memory without knowing the real size of the struct?"
No, compiler doesn't free anything. Free() is just a function with input parameter void *.