Hi, so I'm having a strange problem right now when I'm initializing an array that is a double pointer. The line that is causing me problems is

lines->list = malloc(num_elements * sizeof(char *))

Lines is a struct, and list is a double pointer to a character. So

char **line

All I'm trying to do is initialize my double to hold num_elements in it. There are a couple of questions/problems I'm having when I run gdb and step to this line. One is, is sizeof(char *) supposed to be size 8? And also, when I look at the elements of list, list[0] is empty, list[1] and list[2] have something in it, and list[3] is invalid. This doesn't really make sense to me because num_elements evaluates to 2, so first only list[0] and list[1] should be valid.

Also, I'm not sure if this is useful information, but I've tried just putting actual numbers in for num_elements and sizeof(char *) and it still doesn't work.

One is, is sizeof(char *) supposed to be size 8?

It should be, provided you're writing a 64-bit application.

And also, when I look at the elements of list, list[0] is empty, list[1] and list[2] have something in it, and list[3] is invalid.

We would have to actually take a look at where you're initializing the individual elements of list to be able to tell you why that is. Perhaps somewhere, you're accidentally initializing an element ahead of where you should be, and this might not immediately cause your program to terminate, suprisingly enough.

I look at the elements of list, list[0] is empty, list[1] and list[2] have something in it, and list[3] is invalid.

If num_elements == 2 then attempting to peek at elements other than 0 and 1 is looking beyond the end of the allocated memory. You can do that, but what you will see is some random values that just happen to be in those memory locations. list[3] is shown as invalid quite possibly because the memory at that location is not owned by the process. just because the debugger shows something in list[??] doesn't mean it's valid memory. This has been the cause of countless debugging hours for millions of C programmers.

Well, the reason I'm looking at beyond elements 0 and 1 in gdb is because I have something like this is my code later on

while (list[x] != NULL) {
    /** do stuff **/
}

gdb moves on onto elements 2 on its on and this results in me getting a segfault or some other type of error because I'm moving 1 element past what I should be at which messes things up.

But if that really is the case, should I be doing something after the malloc to set the elements after 0 and 1 to null or something?

You need to set all the elements to NULL after calling malloc(), such as like this:
memset(lines->list,0,num_elements * sizeof(char*))

or call calloc() instead of malloc(), which will do it for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.