0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so if Im understanding this correctly, I'll have to append a terminating character to the end of each inventory after I strncpy to it?
Yes. And you need to have space for it, so declare char inventory[totalRuns][chunkSize + 1];. Well, if you 0-initialise the entire inventory, you don't need to add 0-terminators, since they are already there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.