开发者

Why does pointer to malloc'd area fail unless copied?

开发者 https://www.devze.com 2023-01-07 07:14 出处:网络
I have a pointer to a struct. I c开发者_StackOverflow中文版all a routine that determines whether I need this struct and allocates space for it using malloc, returning the pointer to that area or zero

I have a pointer to a struct. I c开发者_StackOverflow中文版all a routine that determines whether I need this struct and allocates space for it using malloc, returning the pointer to that area or zero if unused.

struct node *node_p;
node_p = need_this();

This works and I can properly access all the elements of the struct. One of the elements of struct node is *next which points to the next node struct and a pointer to a string but it's returning a pointer to a string that doesn't even exist in this routine.

node_p=find_string(node_p->next,"string");

However, this does return a pointer in the struct to the correct string.

struct node *node_p, *node_copy;
node_copy=find_string(node_p->next,"string");

The only difference is using a second pointer instead of the original. Am I doing something wrong here or must it be deeper into the called function? The problem with blaming the called function is I use it in multiple places for months without issue, however the other calls only look for the string and never go to 'next'.

EDIT: Further debugging has shown the problem actually lies with the pointer being passed to find_string and not the returned pointer. That changes the question and the problem so I need to open another question.


In this snippet:

struct node *node_p, *node_copy;
node_copy=find_string(node_p->next,"string");

you dereference node_p when it is not yet initialized (doesn't point to a legally allocated memory block). That's undefined behavior. You should set node_p to a legally allocated memory block of appropriate size first.


You need to allocate memory explicitly for every struct, i.e. allocate a new struct and set next pointer to point to it. Pointers in C prior to initialization point to random place and you never should dereference them. Safe policy would be to init them to be NULLs.

0

精彩评论

暂无评论...
验证码 换一张
取 消