1

I am just trying to use malloc and the code runs fine but visual studios gives me issues with it. Is this how you're supposed to do these things or am I doing something wrong?

The warning shows up right on the line:

chadley->name = "chadley"
#include <stdio.h>
#include <stdlib.h>


typedef struct {
    int age;
    char *name;
} Person;


int main()
{
    Person bradley;
    bradley.name = "bradley";
    bradley.age = 2334444;

    Person *chadley = malloc(sizeof(Person));
    chadley->name = "chadley";
    chadley->age = 234;

    printf("Person object %s of age %d", chadley->name, chadley->age);
}

Error Code: Dereferencing NULL pointer 'chadley'

bturner1273
  • 660
  • 7
  • 18

2 Answers2

3

A Person * can be a null pointer. It refers to the value, not the type.

If it fails to successfully allocate memory, malloc will return a NULL value. You should always check the value returned from malloc before using it.

You can check that the pointer returned is valid doing something like:

Person *chadley = malloc(sizeof(Person));

if (!chadley) {
    /* The allocation failed, don't continue. */
    return 1;
}

chadley->name = "chadley";
chadley->age = 234;
Thomas Jager
  • 4,836
  • 2
  • 16
  • 30
  • 1
    [Lose the cast on `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) and you'll probably earn at least one uptick. – WhozCraig Jul 11 '19 at 18:50
  • `Person *chadley = malloc(sizeof *chadley);` would be more maintainable. – chux - Reinstate Monica Jul 11 '19 at 18:58
  • @chux why do you say this? is there a difference? – bturner1273 Jul 11 '19 at 19:13
  • Are you just saying in case I changed the name of the struct? – bturner1273 Jul 11 '19 at 19:26
  • 1
    @bturner1273: In case you change it's type, yeah. Compare `T *p = malloc( sizeof (T))` to `T *p = malloc( sizeof *p )`. In the first case, if `T` ever changes, you have to make both the declaration and `sizeof` operator match up. In the second, you only have to worry about the declaration. It also makes life easier if you have to worry about whether `T` is another pointer type, or a pointer to an array type, or whatever. – John Bode Jul 11 '19 at 19:28
1
#include <stdio.h>
#include <stdlib.h>


typedef struct {
    int age;
    char *name;
} Person;


int main()
{
    Person bradley;
    bradley.name = "bradley";
    bradley.age = 2334444;

    Person *chadley = malloc(sizeof(Person));
    if (chadley == NULL) return 1;
    chadley->name = "chadley";
    chadley->age = 234;
    printf("Person object %s of age %d", chadley->name, chadley->age);
}

works thank you!

bturner1273
  • 660
  • 7
  • 18