Kntlii
Kntlii

Reputation: 157

C How does Dynamic Memory allocation work

I found the following example:

typedef struct {
    char * name;
    char age;
} person;

person * myperson = malloc(sizeof(person));

myperson->name = "John";
myperson->age = 27;

(http://www.learn-c.org/en/Dynamic_allocation)

I think im allocating 8 Bytes (sizeof(person)) in the example. So i think i blow up the program when i assign "justatestfoobar" to myperson->name...

Can someone explain why and how this works?

Upvotes: 2

Views: 206

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

When you write

 person * myperson = malloc(sizeof(person));

it allocates memory for the myperson variable (pointer), i.e, for the myperson->name and myperson->age member variable themselves.

The memory location, pointed by myperson->name (being a pointer), is not valid, till time. In other words, myperson->name itself is a valid access, but the moment you try to use the content of the memory location pointed by myperson->name, it'll be UB as the pointer value is indeternminate. You need to allocate memory separately to the pointer.

Following that,

 myperson->name = "John";

is valid, as you're storing the starting address of the string literal "John" to the pointer. After this you can use the pointer content. (Remember, as myperson->name point to a string literal, you may not change it.)

To extend this answer, let me state, if you want to copy a string into the memory location pointed by myperson->name, then, first, you need to allocate memory to myperson->name first. For example,

 myperson->name  = malloc(32);    //allocate memory 
 strcpy(myperson->name, "Hello");  //write to that memory

Upvotes: 4

Related Questions