Solved

C Programming: strcpy

Posted on 2013-10-27
1
255 Views
Last Modified: 2013-10-28
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
Comment
Question by:pzozulka
1 Comment
 
LVL 82

Accepted Solution

by:
Dave Baldwin earned 500 total points
ID: 39604830
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now