p0ny
p0ny

Reputation: 315

2d array of strings and Strcpy fault?

I'm having a problem with assigning values to a 2d array of strings. Here's what the code:

  Char array[]= "Nary had a little lamb";
  int chunkSize = 4;
  char inventory[totalRuns][chunkSize];

  subString(result, array,0,0+chunkSize);
  printf("CHUNK 1 = %s\n",result);          //Prints "Nary"
  strncpy(inventory[0],result,chunkSize);
  memset(result, '\0', strlen(result));

  subString(result, array,pos,pos+chunkSize);
  printf("CHUNK 2 = %s\n",result);          // Prints " had"
  strncpy(inventory[1],result,chunkSize);

And the function substring:

char *subString(char* putHere, char* request,int start,int end){
    char* loc = request+start;
    char* end_loc = request+end;

    memcpy(putHere, loc, end_loc-loc);

    return putHere; 

}

When I run this code, the out put is

CHUNK 1 = Nary

CHUNK 2 = had

which is correct, but when I print inventory, I get

inventory[0]=Nary had       //Should be just "Nary"
inventory[1]= had           //correct

Any ideas what Im doing wrong here?

Upvotes: 0

Views: 860

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183968

Your subString does not 0-terminate the destination buffer, and strncpy also doesn't 0-terminate if there is no 0-byte within the given range. Thus your inventory contains unterminated char sequences, and printing prints until printf finds a 0 byte somewhere or crashes due to an access violation.

The memory layout of inventory has inventory[1] directly after inventory[0]'s last char, so printf("%s", inventory[0]); prints both chunks, since the first wasn't 0-terminated. It seems that there was a 0 byte immediately after that in your case, but since inventory wasn't initialised, that is coincidental.

Upvotes: 2

Related Questions