Christopher Christopher - 1 month ago 15
C Question

Pointer initialised to null changing to 0x1

Having a bit of trouble with a c program I am having to work on (has to be in c, not c++).

I have a struct typedef called list. I have this function:

void init(list * l){
l=malloc(sizeof(list));
l->data=NULL;
l->index=NULL;
l->next=NULL;

printf("Pointer= %p\n", (void *) l->next);
}


Back in another file, I have this

list l;
printf("malloc\n");
init(&l);
printf("Pointer= %p\n", (void *) l.next);


The output of this would be (when on the below OS's):

malloc
Pointer= (nil)
Pointer= 0x1


Can anybody explain to me how this suddenly changes from NULL to 0x1? Its really messing me up when I try to use this as 0x1 obviously doesnt equal null and I eventually get segfaults.

This code works fine on my macbook but on CentOS and Ubuntu 16.04 it generates the above output.
Is there anyway I can make sure it stays at NULL? am I been stupid?

Thanks

Answer

Doing list l; already allocates memory for l. Such memory's address can be obtained by &l.

What you are passing to init is essentially a number, an address in memory (e.g., 0x0000). When init gets executed, l has the value of the address (0x0000). The fact that the type of l is list*, means that l is an address (*) to a list object.

malloc allocates new memory (in this case of sizeof(list)) and returns an address (a number) of where that is located. Essentially, the value of l has effectively changed because the address provided by malloc is a different one from the one where you called init.

Removing malloc should fix the problem.

Comments