Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 275
  • Last Modified:

C Programming: strcpy

Why is the code below wrong? It says that strlen() is 4, and printing "req" gives empty string.

char *req = malloc( sizeof(char) * 200);
strcpy(req, "GET ");
strcpy(req, request);
strcpy(req, " HTTP/1.1\r\nHOST: ");
strcpy(req, hostName);
strcpy(req, "\r\n\r\n");

fprintf(fp, "%d\n", strlen(req));
fprintf(fp, "%s\n", req);

Open in new window

0
pzozulka
Asked:
pzozulka
1 Solution
 
Dave BaldwinFixer of ProblemsCommented:
The way you're doing that, you're writing over the characters each time and the last time, "\r\n\r\n", is 4 characters long but they're all control characters.  After the first 'strcpy', you probably want to use 'strcat' to add the remaining characters to the string.
http://man7.org/linux/man-pages/man3/strncat.3.html
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now