Ok, this bit of code is not doing what you want:
struct some_struct *test_struct = malloc(sizeof(some_string);
test_struct->x = 2;
test_struct->y = 3;
test_struct->some_string = "sadlfkajsdflk";
in this case, your *test_struct
is now pointing to a 'memory zone' with the typeof some_sring
size(I think your some_string is char*
).
Malloc(X)
gives you X
space from your program (or process) virtual memory.
When you do:
struct some_struct *test_struct;
You get enough space to store a pointer to some_struct
.
If you do:
malloc(sizeof(struct some_struct));
You have now reserved struct some_struct
space from the virtual memory. But you want to know 'where' that memory is. Thats why you assign it to the pointer:
test_struct = malloc (sizeof(struct some_struct));
[EDIT]I'd write this:" To make your compiler happier you should also include a cast in there to tell the compiler that that space allocated by malloc is gonna be used to store a struct some_struct
:", giving an example right after. But, in fact, that's not true. As you can see in the comments below, @chutsu corrected this, and to convince yourself, check this question.
The 'main' reason is that you're taking a lot of risks in doing it for no advantages at all.
The rest of the code is now corrected: No cast.
A cleaner way to do this would've been typedefing the struct. Then, your code would look like this:
typedef struct some_struct {
int x;
int y;
char *some_string;
}SomeStruct;
SomeStruct *test_struct;
test_struct = malloc(sizeof(SomeStruct));
About the string allocation. You can think like this: Everything created with malloc(and its brothers calloc, realloc...) needs to be free'd!
This happens because all the other variables are local to functions, even the main is a function, and this ones are cleaned when the function terminates.
So, after allocating your struct, if you want space for your string, you'll have to allocate space for it.
test_struct->some_string = malloc((YOUR_STRING_SIZE+SPACE_FOR_THE_STRING_TERMINATOR)*sizeof(char));
with - SPACE_FOR_THE_STRING_TERMINATOR=1
, the \0
character.
Then, if you want to free test_struct
you'll have to free the string first and the struct later, in the reverse order you would lost the pointer to the string and that would leak.
It looks like this:
free(test_struct->some_string);
free(test_struct);
And that's it, you're done.
Hope this helps.