0

I'm trying to extract the request target from the request-line using strncpy. The resulting string contains 3 chars of rubbish on the end of the string and I can't work out why.

Any ideas?

// grab the request-target from the line
 printf("reqTargetStart = %d\n", reqTargetStart);
 printf("reqTargetEnd = %d\n", reqTargetEnd);

 int len = reqTargetEnd - reqTargetStart + 1;            
 char reqTarget[len]; 

  printf("len = %d\n", len);

  strncpy(reqTarget, &line[reqTargetStart], len);

  printf("requested-target: %s\n",reqTarget);
  int size = sizeof(reqTarget) / sizeof(reqTarget[0]);
  int size2 = strlen(reqTarget);
  printf("requested-target len using sizeof: %d\n", size);
  printf("requested-target len using strlen: %d\n", size2);

Output:

GET /hello.php?q=Alice HTTP/1.1
reqTargetStart = 4
reqTargetEnd = 21
len = 18
requested-target: /hello.php?q=Alice 
// ^this has unreadable chars on the end that can't be pasted into the post
requested-target len using sizeof: 18
requested-target len using strlen: 21
2

Needed the terminating null on reqTarget...

// grab the request-target from the line
            printf("reqTargetStart = %d\n", reqTargetStart);
            printf("reqTargetEnd = %d\n", reqTargetEnd);

            int len = reqTargetEnd - reqTargetStart + 1;            
            char reqTarget[len]; 

            printf("len = %d\n", len);

            strncpy(reqTarget, &line[reqTargetStart], len);

            reqTarget[len] = '\0'; // < THIS

            printf("requested-target: %s\n",reqTarget);
            int size = sizeof(reqTarget) / sizeof(reqTarget[0]);
            int size2 = strlen(reqTarget);
            printf("requested-target len using sizeof: %d\n", size);
            printf("requested-target len using strlen: %d\n", size2);

Output:

GET /hello.php?q=Alice HTTP/1.1
reqTargetStart = 4
reqTargetEnd = 21
len = 18
requested-target: /hello.php?q=Alice
requested-target len using sizeof: 18
requested-target len using strlen: 18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .