2

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Kntlii
  • 157
  • 6

1 Answers1

4

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
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Yes, reason for DV? What did I miss? – Sourav Ghosh Apr 30 '16 at 20:09
  • @SouravGhosh I didn't downvote you, and I wouldn't, because it's a fine answer, but because the question is a pure duplicate, there are those who say we really should *not* be answering them, and there are those who believe that people who answer them anyway should be downvoted.(See this thread on meta: http://meta.stackoverflow.com/questions/315018/why-are-stack-overflow-users-more-passionate-about-stack-overflow-than-helping-p ) – Steve Summit Apr 30 '16 at 22:26