Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

c++ - how to set pointer to a memory to NULL using memset?

I have a structure

typedef struct my_s {

   int x;
   ...
} my_T;

my_t * p_my_t;

I want to set the address of p_my_t to NULL and so far this is how I've tried to do this:

memset (&p_my_t, 0, sizeof(my_t*))

This doesn't not look right to me though. What is the correct way of doing this?


Amendment to question - asking a radically more complex question:

Here is what I am trying to do:

  • Two processes, A and B
  • malloc p_my_t in A, B has N threads and can access it
  • Start deleting in A but I can not simply free it since threads in B may still using it.
  • So I call a function, pass address of p_my_t to B to set its address to NULL in B so no other threads in B can use anymore
  • After call back from B, I then free memory in A

NB: there is no standard way to manage memory allocations via shared memory between processes. You will have to do some rather careful thinking about what is going on.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't use memset to initialize a null pointer as this will set the memory to all bits zero which is not guaranteed to be the representation of a null pointer, just do this:

p_my_t = NULL;

or the equivalent:

p_my_t = 0;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...