0

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;
}
1
  • The first one is correct as that one allocates the correct number of bytes to hold the structure. The other two just allocates memory that is the size of a pointer: Either 4 or 8 bytes. You don't really need (struct X*) on the malloc as the result is compatible with all pointer types. Although it will work (and is a style issue), the conventional way to declare a pointer to a struct is struct X x*. Commented Jul 22, 2021 at 15:36

2 Answers 2

1

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 '&'.

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe the basic of pointers and strings would be more useful here, no ?
This did cross my mind too, so yes very likely.
0

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".

1 Comment

It seems to me that you should elaborate a little on static string versus dynamic allocation of the strings, as the provided code may not be intended to deal with const string. Explain for example that a char pointer is at first a pointer and can then point anything (static strings in the program text section, dynamic allocation, string address in a ROM, etc.). Thus, assign a static string to s is fine but implies there should be no more string manipulation from s except if the static assignment was meant to "allocate" static space, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.