davidawad
davidawad

Reputation: 1043

Accessing dynamic memory in a struct pointer

I'm writing some code to interact with dynamic memory that i' creating and i want to know why it's not working.

struct order{
    char *bookTitle;
    double price;
    char *category;
    double remain;
    int custID;
    char processed;
};
typedef struct order order;

struct orderNode{
    order *order;
    struct orderNode *next;
};
typedef struct orderNode orderNode;

Here is the code creatinng an array or orderNodes and trying to access them. The print statement is giving me a segmentation fault. Not sure why.

orderNode **processQueue = malloc(sizeof(orderNode)*numcats) ;
    //sort the orders into their respective categories
    //sortOrders(processQueue, unSortedQueue, numcats);
    processQueue[1]->order->category = "herro" ;
    puts("string set. \n");
    printf("%s\n",processQueue[1]->order->category);
    /* 
    gdb backtrace output.
    #0  strlen () at ../sysdeps/x86_64/strlen.S:106
    #1  0x00007ffff786794c in _IO_puts (str=0x1000000000a2074 <error: Cannot access memory at address 0x1000000000a2074>)
    at ioputs.c:36
    #2  0x000000000040192f in main (argc=4, argv=0x7fffffffdbd8) at main.c:444
    */

Thanks in advance!

Upvotes: 1

Views: 124

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

I think that instead of

orderNode **processQueue = malloc(sizeof(orderNode)*numcats) ;

you mean

orderNode *processQueue = malloc(sizeof(orderNode)*numcats) ;

Also take into account that for each orderNode in the array you have to allocate data member order before trying to access its own data members.

And indices in C start from zero. It seems that in this statement

processQueue[1]->order->category = "herro" ;

you want to access processQueue[0] instead of processQueue[1]

The code could look like

orderNode *processQueue = malloc( sizeof( orderNode ) * numcats );

processQueue[0].order = malloc( sizeof( order ) );
processQueue[0].order->category = "herro";

puts( "string set." );
puts( processQueue[0].order->category );

Upvotes: 4

JS1
JS1

Reputation: 4767

You never allocated any of your order:

orderNode *processQueue = calloc(numcats, sizeof(orderNode)) ;

for (i=0;i<numcats;i++)
    processQueue[i].order = calloc(1, sizeof(order));

Also, I used calloc for the first allocation to make sure all of your next pointers are NULL. I'm not sure what you plan on doing with those next pointers, though.

EDIT: also, as Vlad from Moscow pointed out, processQueue was of the wrong type (I fixed the type above).

Upvotes: 2

Related Questions