0

I am willing to access a particular element present in the coloumn in my SQLite database so in order to achieve this I have used a select statement

char *query = {0};
            strcat(query, "SELECT ");//exception thrown here
            strcat(query, (char*)arr);//The value to be asscessed
            strcat(query, " FROM CARS");

but this is throwing an exception in ucrtbased.dll why?

update

I have referred this answer here and tried this,char* line1 = "SELECT "; char* line2 = (char*)arr; char* line3 = " FROM CARS"; size_t len1 = strlen(line1); size_t len2 = strlen(line2); size_t len3 = strlen(line3); char *query = (char*)malloc(len1 + len2 + len3 + 1); if (!query) abort(); memcpy(query, line1, len1); memcpy(query + len1, line2, len2); query[len1 + len2 + len3] = '\0';

but I found that I've done something wrong(because out put jumps to the else statement which means invalid sqlite statement) which I could not figure it out kindly help me.

I also referred this tutorial @ cplusplus.com but could not figure it out Thank you

Community
  • 1
  • 1
user105127
  • 25
  • 1
  • 4

1 Answers1

1

You have not allocated any memory to query and trying to copy some characters into it. You can create a variable on stack like char query[256] = {0}; if size is known. Else you can allocate memory dynamically using new[] and release it using delete[].

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • So, I should use malloc? for query variable? Thank you – user105127 Apr 25 '16 at 04:59
  • @user105127: Updated answer. – Naveen Apr 25 '16 at 05:20
  • 1
    Wouldn't one be better off to use a `std::string` and then spit out a char* with `.c_str()` ? You avoid allocating memory, freeing memory and get simpler concatenation to boot. – enhzflep Apr 25 '16 at 05:49
  • @enhzflep: `c_str()` returns `const char*`. You can not modify the contents of that. If really needed one can use `std::vector`. – Naveen Apr 25 '16 at 06:12
  • @Naveen . I referred from your answer and I referred the internet and tried something but I'm facing errors kindly help me.I have updated my question. Thank you – user105127 Apr 25 '16 at 07:07
  • @Naveen - yes, I know that. (I was lazy when I omitted the `const` in my last comment - my mistake) It's an sql string - clearly, the purpose of which is to be used to run a query - do you imagine a scenario where one would _want_ to change the string after it was assembled? (I can't) Even if so, wouldn't one just alter the representation held in the `std::string` before emitting another const char* via `.c_str()`? That is to say - I fail to see the benefit of avoiding a `std::string` – enhzflep Apr 25 '16 at 07:18
  • 1
    @enhzflep: Yes, you are right (I dont know what I was thinlking :)).. a simple `std::string` is much better here. – Naveen Apr 25 '16 at 08:28