Tagging your C code as CODE might make this thread more readable than (what you did) tagging it as PHP.
Quote:
Originally Posted by golden_boy615
hello
I am writing a function(in C language in Linux) to initialize an array of a structure from a mysql table by calling a function by reference but I have a problem with call this function by reference .
|
What do you think you mean by "call ... by reference"?
In C++, you can pass parameters by reference. In C you can't.
If your code were passing ATable by reference, it would still have a memory leak, but it would successfully get the data transferred out of the function (which seems to be your main issue).
Since C has no pass by reference, you can get the same semantic effect (with an uglier syntax) by adding an extra layer of indirection.
You have:
Quote:
Code:
void Init_Table(MYSQL *conn,struct ATable* ATable)
...
ATable=(struct ATable*)malloc(num_rows*sizeof(struct ATable));
...
ATable[Curent_Row].id=atoi(row[0]);
sprintf(ATable[Curent_Row].sid,"%s",row[10] ? row[10] : "NULL");
...
...
Init_Table(conn,ATable);
|
An extra layer of indirection would be:
Code:
void Init_Table(MYSQL *conn,struct ATable** ATable)
...
*ATable=(struct ATable*)malloc(num_rows*sizeof(struct ATable));
...
(*ATable)[Curent_Row].id=atoi(row[0]);
sprintf((*ATable)[Curent_Row].sid,"%s",row[10] ? row[10] : "NULL");
...
...
Init_Table(conn,&ATable);
I added an extra
* to every use of ATable in Init_Table and added
& to the point where the outside ATable is passed into the function. That has the same effect as pass by reference would.
Quote:
when it comes out of function it frees that memory
|
False. With or without my change, your code never frees that memory. That is a memory leak.
Without my change, your code loses the pointer to the memory on exit from the function. ATable inside the function is not the same variable as ATable outside the function. So your code had only ATable inside the function pointing to the allocated memory. ATable outside the function never pointed to anything, so it seg faulted on use.
My change gets ATable outside the function to point to the allocated memory. You should also make a change to free that memory when you are done with it.