Thread: Copy character array to char * pointer

  1. #1
    Registered User
    Join Date
    Nov 2007

    Copy character array to char * pointer

    I have an array of characters name "mess_in" and I would like to assign this to a char* pointer. I attempted using strncpy() but am not sure if this is correct. When I run it once this seems to work correctly but subsequent calls do not seem to be copying the right data. Here is my code:

    	/*Assign memory for each of the variables as needed*/
    	request = malloc(BUFSIZ);
    	temp = malloc(256);
    	/*Read in the HTTP request from the client*/
          if( (nr=read(socket, mess_in, BUFSIZ) ) < 0) {
                fprintf(stderr, "Trouble Reading From Client.\n");
                fprintf(stderr, "Errno Value:  %s\n", strerror(errno));
    		return -1;
    	/*Copy the buffer into the request variable*/
         strncat(request, mess_in, strlen(mess_in));

  2. #2
    Registered User
    Join Date
    Nov 2007
    omg shoot me now, lol. I didn't even realize i had strncat when I wanted strncpy. Fixed it!

  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Cambridge, UK
    May be you should also have to include some error checking for your malloc returns. Thats very important!!!

    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Rishon LeZion, Israel
    who said that mess_in is nul-terminated? use the return value of read instead of strlen
    and do not forget to nul-terminate request manually after each strncat if you want next strncat to work properly
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Replies: 7
    Last Post: 05-11-2008, 10:57 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  5. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM