I'm writing a small C program to clean the radius radacct table, removing ended sessions records and inserting on a separated database. The problem is that MySQL C API doesn't have an easy way to insert the result of a query on another database/table directly, you have to build a custom insert statement, I'm trying to do that, I'm using strncpy to copy the fields on the result row to the insert statement char array. It works for just a few records, than it returns me a segmentation fault error, here is the piece of code where the copy is made:

        while(row = mysql_fetch_row(query_result))
                for (i = 0; i < mysql_num_fields(query_result); i++)
                      strncpy(tmp, row[i], MAX_FIELD_LENGTH);
                      printf("%s ", tmp);


tmp is declarated this way:

char tmp[50];

row is a MYSQL_ROW data structure, which is implemented as an array of strings.

Does anybody know whan can be causing that? Or maybem somebody knows a easier way to insert the result of a select on another table.

Thanks in advance.

Recommended Answers

All 4 Replies

Segmentation fault is displayed as error message when you are trying to insert at more than the memory you allocated.

you've declared temp array and it is occupying 50 bytes(depends on the configuration of the system) of memory. So if you are trying to store at the 51st or more location of tmp array it is diplayed as segmentation fault. Try changing the tmp array to 100 or more than that.You may get the desired output.


I've tried to do that, but it still didn't work. The MySQL API is quite good, but there could be an easier way to do that, something like an insert_row function, that would be very useful =).

I've got a clue now, if I pass a MYSQL_ROW member as a parameter to any string manipulating function, the error happens, I've changed the code to just print the strings and it worked, then I've put a strlen too, then the error happened again.

I solved the problem using the mysql_fetch_lengths and strncpy to copy the string to a tmp string and then I added a '\0' at the end of the tmp string.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.