Reputation:
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;
}
Upvotes: 0
Views: 93
Reputation: 11
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 '&'.
Upvotes: 1
Reputation: 182761
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"
.
Upvotes: 0