Thread: How to store string dinamically

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    26

    How to store string dinamically

    Hi to all,

    I have a problem in a little server program written with C.
    This is the code of main:
    Code:
    int main (unsigned argc, char **argv) {
    int sock, client_len, fd, received;
    struct sockaddr_in server, client;
    /* Setup of transport end point */
    if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
     perror("system call socket failed");
     exit(1);
    }
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(SERVER_PORT);
    /* binding of transport end point address*/
    if (bind(sock, (struct sockaddr *)&server, sizeof(server) == -1) {
     perror("system call bind failed");
     exit(2);
    }
    listen(sock, 1);
    /* connection of client */
    while (1) {
     client_len = sizeof(client);
     if ((fd = accept(sock, (struct sockaddr *)&client, &client_len)) < 0) {
      perror("accepting connection");
      exit(3);
     }
     fprintf(stderr, "Connection Opened.\n");
      send(fd, "Wellcome!\n\n", 9, 0);
      send(fd, "Send to me Your strings (The last ended with ..)!\n\n", 44, 0);
      while(terminated)
        {
           received = recv(new_sd, &c, sizeof(c), 0);
           /* Here the control on the end of trasmission '..' */
        } 
      close(fd);
      fprintf(stderr, "Connection closed.\n");
     }
    }
    When the program server run, attend a connection from client; the client (for example a telnet) send your string (many lines) until the last terminate with '..'
    The construnct for receiving is: received = recv(new_sd, &c, sizeof(c), 0);

    If I use only this construct, without the condition while, the program work fine.

    But I must to store each string in a list, in order to process after; how can declare this list ?
    Each string has a variable lenght; how can allocate the memory?

    Someone has suggested to me the use of malloc, but I don't know how to use.

    I hope in Your help; I have worked a little with c++, but with C I have difficulty.

    Thank You and Best Regards
    Nick

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Dynamically allocate memory with malloc(). Also with send() you must specify the length of the string your sending, but send(fd, "Wellcome!\n\n", 9, 0); is 9 chars upto the ! (so \n and \n will not be sent).

    Perhaps go for a 'payload' method, consider the following:

    Code:
    typedef struct payload_t {
    	unsigned long int bytes;
    } payload;
    
    payload p;
    char s[] = "hello world";
    p.bytes = strlen(s);
    
    send(fd, (char *)&p, sizeof(p), 0);
    send(fd, s, p.bytes, 0);
    To send, then read the payload header into the 'payload' struct to work out how much memory you need to allocate...,

    OR, use realloc in a loop reallocating space as you recv'

    eg, (note some design flaws... such as not checking if realloc failed, ect.):
    Code:
    char * recv = 0, c = 0;
    
    int br = 0;				// bytes recv'd
    unsigned int bc = 0;	// bytecount (total exchanged bytes)
    while(br != SOCKET_ERROR)
    {
    	br = recv(fd, &c, 1, 0);
    	recv = realloc(recv, bc);
    	recv[bc] = c;
    	bc++;
    }
    recv = realloc(recv, bc+1);
    recv[bc] = '\0'; // null
    free(recv);
    recv = 0;
    hth
    Last edited by zacs7; 04-05-2007 at 01:19 AM.

  3. #3
    Lean Mean Coding Machine KONI's Avatar
    Join Date
    Mar 2007
    Location
    Luxembourg, Europe
    Posts
    444
    Your problem has already been discussed with lots of detail in this thread. I suggest you read it, the important stuff is from post #21 onwards.

    Basically, what malloc() does is that it allocates a continuous block of memory. As a string is nothing else than an array of characters, the following code allocates a string of size 200:

    Code:
    int stringLength = 200;
    char *myString = malloc(stringLength * sizeof(*myString)); // the salem notation
    //OR
    char *myString = malloc(stringLength * sizeof(char)); // the less good but still good notation
    //OR
    char *myString = malloc(stringLength); // the "i don't care, char is 1 byte" notation
    As you can see, you allocated a block of 200 * the size of 1 char (= 1 byte) bytes and you have a pointer "*myString" pointing to the first element, exactly like an array.

    Let's say your program starts receiving and suddenly you're aware that your array is not big enough to hold the value you've just read (by using a temporary string buffer before putting it in the array), then you use realloc(). realloc() takes an already allocated block of memory and resizes it to the newly desired size:

    Code:
    int stringLength = 200;
    int newStringLength = 300;
    char *myString = malloc(stringLength * sizeof(*myString));
    myString = realloc(myString, newStringLength * sizeof(*myString));
    Since you can never know how big your array needs to be, a good compromise is to always double the size if it's full. To know when it's full, you need to have a counter that holds how many chars there are in the array already.
    Please also note that realloc() usually returns the pointer to the newly resized block of memory but if it fails, it returns NULL, in which case you've lost the pointer to the old block of memory. You could use a temporary pointer to the old block and then verify if realloc was successful.
    Code:
    int stringLength = 200;
    int newStringLength = 300;
    
    char *myString = malloc(stringLength * sizeof(*myString));
    char *p;
    
    if ((myString) == NULL)
    {
        printf("We've got a problem Houston, malloc() failed\n.");
        exit(1);
    }
    
    p = myString;
    myString = realloc(myString, newStringLength * sizeof(*myString));
    if (myString == NULL)
    {
        printf("realloc failed ... \n.");
    }
    
    myString = p; // we saved our old block

  4. #4
    Registered User
    Join Date
    Nov 2006
    Posts
    26
    Hi to all,
    Thank You for reply.
    Nick

  5. #5
    Registered User
    Join Date
    Nov 2006
    Posts
    26
    Hi to All
    Thanks for Your reply
    Nick

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 11:40 AM