Accessing the results array from sqlite3_get_table - c

I'm using Ansi C and sqlite3_get_table; everything works except I can't access the query results vector passed as a pointer to an array. Here's my code...
char **sql_results;
sqlite3_get_table(open_database, sql_query,
&sql_results, &RecordCount, &ColumnCount, &error_msg);
for (int i = 0; i <= (RecordCount + 1)* (ColumnCount); i++)
printf("%10d %10s\n",i, sql_results[i]); //get "EXC BAD ACCESS" message
How do I fix sql_results[i]? Thanks.

I think this piece:
i <= (RecordCount + 1)* (ColumnCount)
is causing you the problems. Did you also try
i < (RecordCount + 1)* (ColumnCount)

You should check that the value returned by sqlite3_get_table is SQLITE_OK; it's not safe to access the result table if it isn't.
You should also be aware that this is a deprecated API. And you should add a call to sqlite3_free_table to release the memory; right now you appear to have a memory leak (or you've already done that, but declined to show us).

Related

How to avoid buffer overflow in c

I tried to setup this code to avoid buffer overflow and I'm not sure why it doesn't work. I'm fairly new to this and help would be appreciated.
I've tried using assert to make sure it ends but i want the assert to succeed
void authenticate (void)
{
char buffer1[8];
int i;
for (i = 0; i < 16; i++)
{
assert (i < sizeof(buffer1));
buffer1[i] = ‘x’;
}
}
expect assert to pass but it fails. Want to fix it without completely rewriting the loop. Thanks!
There seems to be some misunderstanding here on exactly how assert functions. The assert macro performs a runtime check of the given condition. If that condition is false it causes the program to abort.
In this case, the value of i ranges from 0 to 15 inside of the loop. On the iterations where the value of i is less that 8 the assert passes. But once i becomes 8 the assert fails causing the program to abort. The failed assert will not cause the program to for example skip the next loop iteration.
The proper way to handle this is to limit the loop counter to not go out of bounds:
for (i=0; i<sizeof(buf); i++)
The C language by itself doesn't perform bounds checking like some other languages. That's part of what makes it fast. That also means that the language trusts the developer to not do things like read / write out of bounds of an array. Breaking that trust results in undefined behavior. So it's up to you to make sure that doesn't happen.
There are also tools such an valgrind which will help identify mismanagement of memory.
Assert fails as expected. Change counter limit to 8 to pass.
for (i = 0; i < 8; i++)
But perhaps you really want
buf[7]=0;
for (i = 0; i < 8; i++)

Loops not recognizing variables?

I'm new to C and working with CUDA although I don't think this problem is specific to CUDA - I've been able to transfer data to and from the GPU device without any problems and for testing purposes only working with a single thread.
After a long loop calculating f1 and f2, I have this snippet of code:
float price = 0;
float net = 0;
int numTrades = 0;
for (int j = 1; j < dataCol; j++) {
if (((f1[j] > f2[j]) && (f1[j - 1] < f2[j - 1]) && price == 0)) {
price = data[j];
numTrades++;
}
else if (((f1[j] < f2[j]) && (f1[j - 1] > f2[j - 1]) && price != 0)) {
net += data[j] - price;
price = 0;
numTrades++;
}
}
which as far as I can tell doesn't have any problems, except for the fact that it refuses to compile with an "identifier 'price' is undefined" error coming from the first if statement. This snippet is the first place in my code it's mentioned and I've tried initializing with int, float, double, even boolean but still get the same error.
Anyone have any ideas as to what might be causing this?
Tl;dr if things inexplicably break in one location, look for typos above it ( I was missing a semicolon in the previous line. )
TL;DR - Your code snippet looks ok. Issue is most likely elsewhere in your actual code.
Once possible reason, however, as I see it, is your compiler does not support C99 or above. Variable definition in between a function code (Mixed declaration) is allowed onwards C99. In other versions, it should come at the beginning of the function itself. Then, also, you should have received error in
for(int j=1; j<
as this is also a C99 feature, so my above assumption is not likely to be true.
Please show some more code.

Using snprintf to print an array? Alternatives?

Is it at all possible to use snprintf to print an array? I know that it can take multiple arguments, and it expects at least as many as your formatting string suggests, but if I just give it 1 formatting string and an array of values, will it print the entire array to the buffer?
The reason I ask, is because I am modifying source code, and the current implementation only supported one value being placed in a string, but I am modifying it to support an array of values. I want to change the original implementation as little as possible.
If this doesn't work, is there another way someone would recommend to do this? Should I just suck it up and use a for loop (how well would that really work without stringbuffers)?
Essentially: What would be the best way to get all of the values from an array of doubles into the same string for a return?
No, there's no formatting specifier for that.
Sure, use a loop. You can use snprintf() to print each double after the one before it, so you never need to copy the strings around:
double a[] = { 1, 2, 3 };
char outbuf[128], *put = outbuf;
for(int = 0; i < sizeof a / sizeof *a; ++i)
{
put += snprintf(put, sizeof outbuf - (put - outbuf), "%f ", a[i]);
}
The above is untested, but you get the general idea. It separates each number with a single space, and also emits a trailing space which might be annoying.
It does not do a lot to protect itself against buffer overflow, generally for code like this you can know the range of the inputs and make sure the outbuf is big enough. For production code you would need to think about this of course, the point here is to show how to solve the core problem.
I decided to go with this:
int ptr = 0;
for( i = 0; i < size; i++)
{
ptr += snprintf(outbuf + ptr, sizeof(outbuf) - ptr, "%.15f ", values[i]);
}
slightly different, but to the same effect as in #unwind 's solution. I got this idea from the reference page for snprintf()

What is causing my code to be non-deterministic?

I might've gone crazy here, but I keep recompiling the exact same code, and get different answers. I'm not using any random values at all. I am strictly staying to floats and 1D arrays (I want to port this to CUDA eventually).
Is it possible on the compiler side that my same code is being redone in a way that makes it not work at all?
I run the .exe by just clicking on it and it runs fine, but when I click "compile and run" (Dev C++ 4.9.9.2) none of my images come out right. ...although sometimes they do.
...any insight on how I fix this? If I can provide any more help please tell me.
Much Appreciated.
Edit:
Here's the block of code that if I comment it out, everything runs sort of right. (Its completely deterministic if I comment this block out)
-this is a electromagnetic simulator, if that helps at all:
//***********************************************************************
// Update HZ in PML regions (hzx,hzy)
//***********************************************************************
boundaryIndex = 0;
for (regionIndex = 1; regionIndex < NUMBEROFREGIONS; regionIndex++) {
xStart = regionData[regionIndex].xStart;
xStop = regionData[regionIndex].xStop ;
yStart = regionData[regionIndex].yStart;
yStop = regionData[regionIndex].yStop ;
for (i = xStart; i < xStop; i++) {
for (j = yStart; j < yStop; j++) {
hzx = hz[i*xSize+j] - hzy[boundaryIndex]; // extract hzx
hzx = dahz[i*xSize+j] * hzx + dbhz[i*xSize+j] * ( ey[i*(xSize+1)+j] - ey[(i+1)*(xSize+1)+j] ); // dahz,dbhz holds dahzx,dbhzx
hzy[boundaryIndex] = dahzy[boundaryIndex] * hzy[boundaryIndex] + dbhzy[boundaryIndex] * ( ex[i*ySize+j+1] - ex[i*ySize+j] );
hz[i*xSize+j] = hzx + hzy[boundaryIndex]; // update hz
boundaryIndex++;
} //jForLoop /
} //iForLoop /
} //
where, NUMBEROFREGIONS is constant (8), Xsize is defined at compile time (128 here).
Well some code examples would help! But this is a classic symptom of un-initialized variables.
You are not setting some important variables (indexes to 0, switches to True etc.) so your program picks up whichever values are hanging around in memory each time you run.
As these are effectively random values you get different results each time.
Is there an indexing error with your simulated two-dimensional array? Is ey supposed to be xSize or xSize+1 wide?
dahz[i*xSize+j] * hzx +
dbhz[i*xSize+j] * ( ey[i*(xSize+1)+j] -
ey[(i+1)*(xSize+1)+j] );
Your index treats 2D array ey as being xSize+1 wide. The code for array ex treats it as being ySize wide.
dbhzy[boundaryIndex] * ( ex[i*ySize+j+1] - ex[i*ySize+j] );
You are potentially invoking undefined behaviour. There are a number of things that are undefined by the C language standard. Some of these cases can be caught by the compiler and you may be issued a diagnostic, others are harder for the compiler to catch. Here is just a few things that have undefined behaviour:
Trying to use the value of an uninitialised variable:
int i;
printf("%d\n", i); // could be anything!
An object is modified more than once between sequence points:
int i = 4;
i = (i += ++i); // Woah, Nelly!
Reading or writing past the end of an allocated memory block:
int *ints = malloc(100 * sizeof (int));
ints[200] = 0; // Oops...
Using printf et. al but providing the wrong format specifiers:
int i = 4;
printf("%llu\n", i);
Converting a value to a signed integer type but the type cannot represent the value (some say this is implementation defined and the C language specification seems ambiguous):
signed short i;
i = 100.0 * 100.0 * 100.0 * 100.0; // probably won't fit
Edit:
Answered before OP provided code.
Are you compiling it in debug mode or release mode? Each one of these have different way how they initialize the heap and memory.
As everybody said without some code of what is wrong we can't help you a lot.
My best gest from what you just explained is that your creating pointers on non allocated memory.
something like this
APointer *aFunction(){
YourData yd = something;//local variable creation
return yd;
}
main(){
APointer *p = aFunction();
}
Here p is a pointer to something that was a local varaible in aFunction and got destroyed as soon as it left the function, this will sometime by PURE LUCK still point to the right data that hasn't been written over, but this memory space will eventual be changed and your pointer will be reading something different completly random.

STM32 printf and RTC

* UPDATE *
Here is what I found. Whenever I had that function in there it wouldn't actually make the code lock up. It would actually make the read RTC I²C function very slow to execute, but the code would still run properly, but I had to wait a really long time to get past every time I read the RTC.
So there is an alarm interrupt for the RTC and this was triggering other I²C interactions inside the ISR, so it looks like it was trying to do two I²C communications at the same time, therefore slowing down the process. I removed the functions in the ISR and it's working now. I will keep investigating.
I am having this problem when programming an STM32F103 microcontroller using IAR 5.40. I have this function that if I try to printf a local variable it causes the code to freeze at another point way before it even gets to that function in question.
What could possibly be causing this?
This is the function:
u8 GSM_Telit_ReadSms(u8 bSmsIndex)
{
char bTmpSms[3] = {0};
itoa(bSmsIndex, bTmpSms, 10); // Converts the smsindex into a string
printf("index = %s\n", bTmpSms); // This printf caused the code to get stuck in the RTC // byte read function!
GSM_Telit_RequestModem("AT+CMGR=""1", 10, "CMGR", 5, 0);
return 1;
}
I tried this as well and this does not cause the lock I experienced:
u8 GSM_Telit_ReadSms(u8 bSmsIndex)
{
char bTmpSms[3] = {0};
itoa(bSmsIndex, bTmpSms, 10);
printf("index = 2\n");
GSM_Telit_RequestModem("AT+CMGR=""1", 10, "CMGR", 5, 0);
return 1;
}
There is no optimization enabled whatsoever and the code gets stuck when trying to read a byte out of my I²C RTC, but as soon as I remove this printf("index = %s\n", bTmpSms); or use this one instead printf("index = 2\n"); then everything is happy. Any ideas?
The bSmsIndex will never be more than 30 actually and even then the lock up happens wayyyy before this function gets called.
char bTmpSms[3] only has space for "99". If your bSmsIndex is 100 or greater, you will be trying to write to memory that doesn't belong to you.
Edit after the update
I don't have a reference to itoa on my local machine, but I found this one ( http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/ ). According to that reference, the destination array MUST BE LONG ENOUGH FOR ANY POSSIBLE VALUE. Check your documentation: your specific itoa might be different.
Or use sprintf, snprintf, or some function described by the Standard.
Some ideas:
If itoa() is not properly NUL-terminating the string, then the call to printf may result in the machine looking for the NUL forever.
pmg has a very good point.
Also, consider what type the first argument to itoa() is. If it's signed and you're passing in an unsigned integer, then you may be getting an unexpected minus sign in bTmpSms. Try using sprintf() instead.
The change in code is moving the rest of your code around in memory. My guess is that some other part of the code, not listed here, is bashing some random location; in the first case that location contains something critical, in the second case it does not.
These are the worst kinds of problems to track down*. Good luck.
*Maybe not the worst - it could be worse if it were a race condition between multiple threads that only manifested itself once a week. Still not my favorite kind of bug.
It seems that if I don't initialize the variable bTmpSms to something the problem occurs.
I also realized that it is not the printf that is the problem. It is the itoa function. It got me to check that even though I didn't think that was the problem, when I commented the itoa function then the whole code worked.
So I ended up doing this:
u8 GSM_Telit_ReadSms(u8 bSmsIndex)
{
char bTmpSms[4] = "aaa"; // I still need to find out why this is !!!
itoa(bSmsIndex, bTmpSms, 10); // Converts the smsindex into a string
printf("index = %s\n", bTmpSms); // This printf caused the code to get stuck in the RTC // byte read function!
GSM_Telit_RequestModem("AT+CMGR=""1", 10, "CMGR", 5, 0);
return 1;
}
This is the itoa function I got:
char itoa(int value, char* result, int base)
{
// Check that the base if valid
if (base < 2 || base > 36) {
*result = '\0';
return 0;
}
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do
{
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsr
qponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while (value);
// Apply negative sign
if (tmp_value < 0)
*ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr)
{
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return 1;
}
What's the value of bSmsIndex you're trying to print?
If it's greater than 99 then you're overrunning the bTmpSms array.
If that doesn't help, then use IAR's pretty good debugger - I'd drop into the assembly window at the point where printf() is being called and single step until things went into the weeds. That'll probably make clear what the problem is.
Or as a quick-n-dirty troubleshoot, try sizing the array to something large (maybe 8) and see what happens.
What's the value of bSmsIndex?
If more than 99 it will be three digits when converted to a string. When zero terminated, it will be four characters, but you've allocated only three to bTmpSms so the null may get overwritten and the printf will try to print whatever is after bTmpSms until the next null. That could access anything, really.
Try to disassemble this area with index = 2 vs. index = %s.

Resources