Int Array Being Changed In Function

These two arrays
1
2
3
4
/* One Hour Set */
   int one_set_begin[] = {4, 7, 10, 13, 16, 19, 20, 22, 23, 23};
/* One Hour Set */
   int one_set_end[] =   {6, 9, 12, 15, 18, 20, 21, 23, 23, 24};


...are being passed into this function
 
int create_statement(char hd_begin[2], char *statement, const int *begin, const int *end)


Here's some of the code within that function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
char class_no[5];
   int total_in_set = 10;
   int i, j, k;

   for(j = 0; j <= total_in_set-1; j++){
      strcat(statement, "SELECT * FROM (SELECT * FROM dj_music WHERE hd='");
      strcat(statement, hd_begin);

      if(strcmp(hd_begin, "A") == 0)
         strcpy(hd_begin, "B");
      else
         strcpy(hd_begin, "A");

      strcat(statement, "' AND (");

      for(k = begin[j]; k < end[j]+1; k++) {
         strcat(statement, "(classnumber=");
         sprintf(class_no, "%d", k);
         strcat(statement, class_no);
         strcat(statement, ")");

         if(k < end[j])
            strcat(statement, " OR ");
      }
   <snip>


When it gets down to here
 
for(k = begin[j]; k < end[j]+1; k++) {


...begin[0] (for example) is 134535230, but before that line it read properly as 4.

Why is my int array being changed? Thanks.
How big is statement? Is it being overritten with the strcat/strcpy functions?
Looks to me like it might be memory corruption. You're probably going out of bounds on one of your string buffers and text is "spilling" into your begin/end buffers. Probably 'statement' simply isn't large enough to hold all of the text you're copying to it.

You might want to consider switching from C style strings over to C++'s string and stringstream . This will make memory corruption caused by buffer overflow virtually impossible:

(also seems weird that you're using hd_begin as a string when really it's just a single char):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int create_statement(char hd_begin, stringstream& statement, ...)
{
  statement << "SELECT * FROM (SELECT * FROM dj_music WHERE hd='";
  statement << hd_begin;

  if(hd_begin == 'A')  hd_begin = 'B';
  else                 hd_begin = 'A';

  statement << "'AND (";

  for(k = begin[j]; k <= end[j]; ++k)
  {
    statement << "(classnumber=" << hd_begin << k << ')';

    if(k < end[j])
      statement << " OR ";
  }
  // ... 


1
2
3
4
5
6
7
8
9
10
stringstream statement(stringstream::in | stringstream::out);
create_statement(hd_begin,staement,one_set_begin,one_set_end);

// to get a c-style string from that, get a std::string first
string str = statement.str();

// then get a c-string
const char* buffer = str.c_str();

// 'buffer' remains valid until 'str' loses scope. 
OK, thanks for the help guys. Got it to work correctly.
Topic archived. No new replies allowed.