0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Name *NameFunc(struct Name *);

struct Name
{
    char *Fname;
    char *Lname;
};

int main()
{

    struct Name *name1, *name2;

    name1 = (struct Name *)malloc(sizeof(struct Name));
    //name2 = (struct Name *)malloc(sizeof(*name2));

    name1->Fname = (char *)malloc(50 * sizeof(char));
    name1->Lname = (char *)malloc(100 * sizeof(char));
    strcpy(name1->Fname, "Akhil");
    strcpy(name1->Lname, "Sambaraju");
    printf("%s %s\n", name1->Fname, name1->Lname);

    name2 = NameFunc(name2);

    printf("%s %s", name2->Fname, name2->Lname);

    return 0;
}
struct Name *NameFunc(struct Name *name)
{

    name->Fname = "Akhil";
    name->Lname = "Sambaraju 2.0";

    return name;
}

OUTPUT: Akhil Sambaraju Akhil Sambaraju 2.0

How is this code running properly even though i havent allocated memory to 'name2'? After some messing around with commenting, i found that the function call NameFunc() has nothing to do with it. But 'name1' has. If i dont allocate memory to name1 using malloc, it doesnt print out anything on cmd. When I intialise name2 to NULL, it just prints out "Akhil Sambaraju" i:e name1. Why does allocating memory to name1, allocate memory to name2 as well(when not initialised)? PS: why does intialising fname and lname to NULL in struct Name give an error?

Akhilalot
  • 13
  • 2
  • Pointers and arrays are different things. You may like to read section 6 of the [comp.lang.c faq](http://c-faq.com/). In `name->Fname = "Akhil";` you have a pointer (`name->Fname`) and an array (`"Akhil"`). The array is implicitly converted to a pointer for the assignment. – pmg Aug 28 '20 at 13:46
  • 3
    You invoked *undefined behavior* by using (indeterminate) value of uninitialized non-static local variable, so *anything* can happen. Telling reason of this specific obseved behavior will require deep inspection of your envornment (compiled assembly code, how stack is used in each functions, etc). – MikeCAT Aug 28 '20 at 13:47
  • Uninitialized variables may have *any* value, depending on how the compiler is feeling that day. This includes pointers. name2 could point to the same place as name1, for example, if the compiler feels like that. – user253751 Aug 28 '20 at 13:56
  • Just to drive the point home, here is your exact program crashing https://wandbox.org/permlink/VUx8YZONw7Q3IWrR – anastaciu Aug 28 '20 at 14:02
  • Here's the relevant explanation: [What is undefined behavior and how does it work?](https://software.codidact.com/questions/277486). – Lundin Aug 28 '20 at 14:02

0 Answers0