If you initialize a pointer (trav) and assign it another pointer, should you and what happens if you free trav? thank you!

node *table[N] = { NULL };
trav = table[i];

Also, should malloc be called for table array? When?


First, you should ALWAYS initialize a pointer when created, either to NULL or if it's appropriate at the time, initialize with malloc. Otherwise, the pointer will contain garbage data that, if accessed, will result in a seg fault, or if you're really unlucky, will corrupt program memory, just by having a random address that's valid.

If you assign one pointer's value to another, as in trav = table[i]; then both pointers will point at the same memory space. In this case, if you free(trav); the actual memory pointed at will be freed, but both pointers will actually continue to hold the address. If you then try to use that address, from either pointer, the results are unpredictable, but most likely will be a seg fault.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .