Hi
if i have a for loop and inside the for loop i have a pointer. the declaration, allocating of memory and freeing the pointer is done within the for loop. Will there be any problem? Am I treating the pointer as a local pointer?
Hi
if i have a for loop and inside the for loop i have a pointer. the declaration, allocating of memory and freeing the pointer is done within the for loop. Will there be any problem? Am I treating the pointer as a local pointer?
Should not be a problem. Can you please share the code so as to get more clarity on the situation?
Basically its like this. the function test_FillStruct will allocate memory inside the function, hence passing in address of the pointer.Code:for(h=0;h<10;h++) { testStruct_t* ptyTestStruct; if(test_FillStruct(&ptyTestStruct)!=test_SUCCESS) { free(ptyTestStruct); } }
You wont have a problem, but you also wont have access to the pointer or what it points to outside that for loop. You are correctly passing the address of ptyTestStruct assuming that test_FillStruct actually allocates memory, something like
Code:*ptyTestStruct = malloc(sizeof(**ptyTestStruct));
@anduril462 THanks! yup that was my intention of not having access to the pointer outside that for loop. My worry was that I am not sure whether the pointer declared within each loop will affect the pointers declared for subsequent loops
Ya, as of this code, there should not be any problem.
Can you post the function 'test_FillStruct()' ??
The curly braces for the for loop create a new scope, similar to that of a function. The variable ptyTestStruct is only valid in that scope. Be careful, since you could still have a memory leak if you allocate in each loop and don't always free. Once the for loop is over, the ptyTestStruct variable ceases to exist, so you can't pass it to free.