Khan2011
Khan2011

Reputation: 45

odd program behavior after adding one instruction in C

Actually, I have asked another question with the same code, but this is very different. I have this code below that displays a very annoying behavior. I've included as much comment in the code as I can so that you can have an idea of what's going on.

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

/* This is a struct describing properties of an element */
struct element{
    int age;
    char* name;
};

/* This struct contains a pointer to a pointer on a element "struct element" */
struct person{
    struct element** p;
    size_t size;
    unsigned int id;
};

/* This function initializes a struct person by allocating memory for it */
struct person* init(int _size)
{
    if(_size == 0)
    {
         printf("You gonna have to make some choices \n");
         exit(1);
    }
    struct person* sample = (struct person* )malloc(_size*sizeof(struct person));
    sample->p = (struct element** ) malloc(_size*sizeof(struct element*));
    sample->id = 0;
    sample->size = _size;
    return sample;
}

/* use this function to insert a new element in the struct */
void insert(struct person* sample, char* _name, int _age)
{
    if (sample->id >= sample->size) {
        sample->p = (struct element** ) realloc(sample->p, (sample->size*2) * sizeof(struct element*));
        if(sample->p == NULL){
            printf("Get a new RAM buddy \n");
            exit(1);
        }
    }
    sample->p[sample->id]->name = _name; 
    sample->p[sample->id]->age = _age;  /* of course, this will cause trouble too because it has the same construct as the previous one */
    sample->id++;
}


/* main entry */
int main(int argc, char** argv)
{
    int i = 0;
    struct person* student = init(10); /* Allocating space for 10 students */
    insert(student, "baby", 2);
    insert(student, "dady", 33);
    /* if you remove this line, the program runs, but GDB will signal a segmentation fault. If you keep it, the program will freeze and GDB will behave as expected */
    /* I don't understand why this is happening!!!??? */
    insert(student, "grandma", 63);
    printf("Your name is %s and your age is %d \n", student->p[1]->name, student->p[1]->age);  
    /* When you only insert two elements, use the results here to match with GDB's results*/
    printf("student->p: %p \n", &student->p);
    printf("student->p[0]: %p \n", &student->p[0]);
    printf("student->p[1]: %p \n", &student->p[1]);
    printf("student->p[0]->age: %p \n", &student->p[0]->age);
    printf("student->p[0]->name: %p \n", &student->p[0]->name);
    /* Won't work for more than two elements inserted */    
    for(i = 0; i < 2; i++){
        printf("Your name is %s and your age is %d \n", student->p[i]->name, student->p[i]->age);
    }

    return 0;
}

I hope you can figured out what's going on. Here is a part of a debugging session.

(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: C:\Users\NTWALI\Desktop\tests\help\bin\Debug/help.exe
[New thread 11408.0x1228]
Error: dll starting at 0x770a0000 not found.
Error: dll starting at 0x76ab0000 not found.
Error: dll starting at 0x770a0000 not found.
Error: dll starting at 0x76d40000 not found.

Program received signal SIGSEGV, Segmentation fault.
0x0040146f in insert (sample=0x6816c0, _name=0x409031 "ntwali", _age=22) at C:\Users\NTWALI\Desktop\tests\help\main.c:44
44          sample->p[sample->id]->name = _name; 
(gdb) p sample
$4 = (struct person *) 0x6816c0
(gdb) p sample->p
$5 = (struct element **) 0x681750
(gdb) p sample->p[0]
$6 = (struct element *) 0xbaadf00d
(gdb) p sample->p[1]
$7 = (struct element *) 0xbaadf00d
(gdb)

As you see in the code comment's, the data the program gives when it works, don't match with what one gets with GDB.

Thanks for helping.

Upvotes: 0

Views: 221

Answers (4)

AndersK
AndersK

Reputation: 36092

here you are using p[] without first initializing it to point to anything. you have only allocated space for the pointers but haven't initialized them to point to anything. So when you do

sample->p[sample->id]->name = _name; 
sample->p[sample->id]->age = _age;

p is pointing somewhere in memory and you are modifying what it points to.

instead, insert a

sample->p[sample->id] = malloc(struct element);
sample->p[sample->id]->name = _name; 
sample->p[sample->id]->age = _age;

and it should work

PS. normally you don't cast malloc in C

Upvotes: 0

caf
caf

Reputation: 239321

The root cause of your problem is that you are allocating pointers to struct element, but those pointers are uninitialised - you're not allocating any actual struct element objects. When you dereference those invalid pointers, you get undefined behaviour.

There is also no need to allocate _size of the struct person structs - you only ever use one. Your struct person should look like (note type of p is different):

struct person{
    struct element *p;
    size_t size;
    unsigned int id;
};

and your init() function should then look like:

struct person* init(int _size)
{
    if(_size < 1)
    {
         printf("You gonna have to make some choices \n");
         exit(1);
    }
    struct person* sample = malloc(sizeof *sample);
    sample->p = malloc(_size * sizeof sample->p[0]);
    sample->id = 0;
    sample->size = _size;
    return sample;
}

The insert() function should look like:

void insert(struct person* sample, char* _name, int _age)
{
    if (sample->id >= sample->size) {
        sample->size *= 2;
        sample->p = realloc(sample->p, sample->size * sizeof sample->p[0]);
        if(sample->p == NULL){
            printf("Get a new RAM buddy \n");
            exit(1);
        }
    }
    sample->p[sample->id].name = _name; 
    sample->p[sample->id].age = _age;  /* of course, this will cause trouble too because it has the same construct as the previous one */
    sample->id++;
}

The main function should then use student->p[i].name and student->p[i].age to access the data.

Upvotes: 0

otto
otto

Reputation: 1158

If the presence of a debugger alters the way your program behaves, you are very likely misusing memory or threads. Just like daven11 points out, you are not allocating the elements itself.

Upvotes: 3

daven11
daven11

Reputation: 3035

You haven't allocated any memory for an element as far as I can see. Here you allocate memory for a pointer to an element:

sample->p = (struct element** ) malloc(_size*sizeof(struct element*));

Upvotes: 3

Related Questions