Link to home
Start Free TrialLog in
Avatar of uri22
uri22

asked on

allocate structure pointer

I have a c program with declaration of :
struct myStr *myStrPtr
The struct is :
struct myStr
{
cahr a[2]
int  b
char c[3]
...
}
How do I allocate the strcucture pointer
Thanks
Uri22
ASKER CERTIFIED SOLUTION
Avatar of ct.smith
ct.smith

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of uri22
uri22

ASKER

Thanks
Where is the correct place to do the malloc?
I have few function uses the struct.
Do I have to malloc in each of them ?
You should only malloc once.  Once you've allocated a block of memory, it is there until you've deallocated it.  malloc will assign a new block of memory to the pointer every time you call it.  If you allocate a new block of memory, the previous block is lost, but still allocated, this is usually called a "memory leak".  Nothing can use that piece of memory that's been lost until the program exits.

for example:
ptr = malloc(sizeof(myStr));  /* allocate memory block 1*/
ptr = malloc(sizeof(myStr));  /* allocate memory block 2, block 1 is now lost */

If you want to use a pointer over again, free the memory before the next allocation.

The easiest way to manage this is to just use malloc when you declare the pointer.

struct myStr* ptr = malloc(sizeof(myStr));

Extra advice:
If you're not comfortable with dynamic memory allocation, you may just want to stick with static memory (no pointers).  It's really important to understand the underlying memory organization before dynamic memory usage becomes easy.
uri22,
Could you please accept a comment as the answer if your question has been resolved. If you need additional help, please reject the proposed answer and ask for additional information. You can also choose to delete the question if you feel the comments have not helped in any way or have another good reason for deleting it.

RedCCameleon,
Community Support Moderator @ Experts Exchange
Force/accepted by

Netminder
Community Support Moderator
Experts Exchange