Help with segfault - Programming On Unix

Users browsing this thread: 3 Guest(s)
robotchaos
Long time nixers
So I'm barely getting into C and wanted to start with something that goes step by step, fairly recent, and then going to run through K&R2. Chose Zed A. Shaw's Learn C the Hard Way. Exercise 16 ran perfect for me. Until I rebuilt my laptop with Debian on it. I was running Solus. Now when I try to run the following code, it segfaults right after completing the printf statement on line 51. I tried running it through gdb and I get an error saying strlen.S No such file or directory, so I'm not sure what I'm missing to be able to debug this small program. Weird thing is, if I run it through valgrind, it does NOT segfault. It also does not segfault on my work Fedora install. This is verbatim code for exercise 16 from the book.

Is there a perfectly valid reason this code would segfault, or is my machine misconfigured?

Code:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>

struct Person {
    char *name;
    int age;
    int height;
    int weight;
};

struct Person *Person_create(char *name, int age, int height,
        int weight)
{
    struct Person *who = malloc(sizeof(struct Person));
    assert(who != NULL);

    who->name = strdup(name);
    who->age = age;
    who->height = height;
    who->weight = weight;

    return who;
}

void Person_destroy(struct Person *who)
{
    assert(who != NULL);

    free(who->name);
    free(who);
}

void Person_print(struct Person *who)
{
    printf("Name: %s\n", who->name);
    printf("\tAge: %d\n", who->age);
    printf("\tHeight: %d\n", who->height);
    printf("\tWeight: %d\n", who->weight);
}

int main(int argc, char*argv[])
{
    //make two people structures
    struct Person *joe = Person_create("Joe Alex", 32, 64, 140);

    struct Person *frank = Person_create("Frank Blank", 20, 72, 180);

    // print them out and where they are in memory
    printf("Joe is at memory location %p:\n", joe);
    Person_print(joe);

    printf("Frank is at memory location %p:\n", frank);
    Person_print(frank);

    //make everyone age 20 years and print them again
    joe->age += 20;
    joe->height -= 2;
    joe->weight += 40;
    Person_print(joe);

    frank->age += 20;
    frank->weight += 20;
    Person_print(frank);

    //destroy them both so we clean up
    Person_destroy(joe);
    Person_destroy(frank);

    return 0;
}


Messages In This Thread
Help with segfault - by robotchaos - 27-07-2017, 06:57 PM
RE: Help with segfault - by xcko - 28-07-2017, 12:12 AM
RE: Help with segfault - by z3bra - 28-07-2017, 03:22 AM
RE: Help with segfault - by robotchaos - 28-07-2017, 01:02 PM
RE: Help with segfault - by z3bra - 28-07-2017, 01:25 PM
RE: Help with segfault - by pranomostro - 28-07-2017, 03:37 PM
RE: Help with segfault - by robotchaos - 28-07-2017, 05:00 PM
RE: Help with segfault - by z3bra - 28-07-2017, 05:52 PM
RE: Help with segfault - by robotchaos - 28-07-2017, 06:39 PM