Copy character array to char * pointer

This is a discussion on Copy character array to char * pointer within the C Programming forums, part of the General Programming Boards category; I have an array of characters name "mess_in" and I would like to assign this to a char* pointer. I ...

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    96

    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:

    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
    Posts
    96
    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
    Location
    Cambridge, UK
    Posts
    1,682
    May be you should also have to include some error checking for your malloc returns. Thats very important!!!

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

  4. #4
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,474
    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
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21