Dynamic strings in C?

This is a discussion on Dynamic strings in C? within the C Programming forums, part of the General Programming Boards category; Hi guys One of the things about C that I have also been a little worried about is when using ...

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    140

    Dynamic strings in C?

    Hi guys

    One of the things about C that I have also been a little worried about is when using strings. Say that I want to ask the user to input a sentence:

    Code:
    #include <stdio.h>
    
    #define length 100
    
    int main()
    {
    	int i=0;
    	char str[length];
    	
    	while((i < length-1) && (str[i]=getche())!=13)
    	{
    		i++;
    	}
    
    	str[i]='\0';
    	
    	return 0;
    }
    Perhaps the user only enters a sentence 2 characters long. Now, aren't the other 98 characters just taking up unnecessary space?

    What is the closest one can get to dynamically allocate a string in C, such that this waste of memory is not present in a program?

    Best,
    Niles.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Quote Originally Posted by Niels_M
    Perhaps the user only enters a sentence 2 characters long. Now, aren't the other 98 characters just taking up unnecessary space?
    Yes, though this might not matter.

    Quote Originally Posted by Niels_M
    What is the closest one can get to dynamically allocate a string in C, such that this waste of memory is not present in a program?
    One approach is to use malloc() and/or realloc(), expand the dynamic array as needed, and after one is done with reading, trim it down to the required size. Of course, you should also free() appropriately.

    By the way, getche is non-standard and it would be better to use character literals instead of magic numbers as such 13.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Aug 2009
    Posts
    140
    Quote Originally Posted by laserlight View Post
    One approach is to use malloc() and/or realloc(), expand the dynamic array as needed, and ....
    Thanks. I have been reading about these functions:

    1) When using malloc like in

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
    int *temp;
    
    temp = malloc(sizeof(int));
    temp[0]=1;
    temp[1]=2;
    temp[2]=3;
    
    return 0;
    }
    an error is not produced. Why is that? The command malloc(sizeof(int)) only reserves memory for 1 integer, but my array can continue beyond that?

    2) Is there any logic behind the fact that I do not need to typecast the void-pointer malloc returns? Or is this just how C works?

    3) When I use the free()-command, I free the piece of memory malloc has reserved. Does this mean that the void-pointer orignally returned by malloc cannot point to the memory anymore?

    Best,
    Niles.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Quote Originally Posted by Niels_M
    an error is not produced. Why is that? The command malloc(sizeof(int)) only reserves memory for 1 integer, but my array can continue beyond that?
    You're accessing the array out of bounds.

    Quote Originally Posted by Niels_M
    2) Is there any logic behind the fact that I do not need to typecast the void-pointer malloc returns? Or is this just how C works?
    It is just how C works.

    Quote Originally Posted by Niels_M
    3) When I use the free()-command, I free the piece of memory malloc has reserved. Does this mean that the void-pointer orignally returned by malloc cannot point to the memory anymore?
    It still contains the address, except that the address is no longer that of the dynamic array because the dynamic array is no more. Maybe it will get reused for another dynamic array, but maybe not.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Aug 2009
    Posts
    140
    Quote Originally Posted by laserlight View Post
    1)You're accessing the array out of bounds.


    2)It is just how C works.


    3)It still contains the address, except that the address is no longer that of the dynamic array because the dynamic array is no more. Maybe it will get reused for another dynamic array, but maybe not.
    Thanks. Regarding realloc, from http://www.cplusplus.com/reference/c...dlib/realloc/:

    "The function may move the memory block to a new location, in which case the new location is returned."

    If that is the case (i.e. that the memory block may be moved, then I should free both "data" and "temp" when I have the following piece of code, right?

    Code:
    temp=realloc(data, 2*sizeof(char));

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Quote Originally Posted by Niels_M
    If that is the case (i.e. that the memory block may be moved, then I should free both "data" and "temp" when I have the following piece of code, right?
    No, if necessary, realloc() will deallocate the old dynamic array for you.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Please RTFM.

  8. #8
    Registered User
    Join Date
    Aug 2009
    Posts
    140
    Quote Originally Posted by laserlight View Post
    No, if necessary, realloc() will deallocate the old dynamic array for you.
    Thanks.

    Quote Originally Posted by Bayint Naung View Post
    Please RTFM.
    I will, sorry.

  9. #9
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,596
    Beware that if realloc fails, it would return NULL. And that means if you blindly assign the return of realloc to your pointer that you got from malloc, you will overwrite the old value and get a memory leak. Be careful.
    If realloc fails, possibly free what you got from malloc.
    Last edited by Elysia; 07-21-2010 at 04:56 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Quote Originally Posted by Elysia
    Beware that if realloc fails, it would return NULL. And that means if you blindly assign the return of realloc to your pointer that you got from malloc, you will overwrite the old value and get a memory leak. Be careful.
    If realloc fails, possible free what you got from malloc.
    Note that that cplusplus.com article's example makes this mistake, although it is forgivable by virtue of the fact that the program just bails out by ending its life (seppuku?) should realloc return a null pointer.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating and Using a dynamic array of C strings?
    By swbluto in forum C Programming
    Replies: 11
    Last Post: 11-17-2009, 06:09 PM
  2. Strings and Dynamic Memory
    By grooveordie in forum C Programming
    Replies: 3
    Last Post: 10-20-2008, 02:08 PM
  3. beginner: dynamic array of strings
    By pc2-brazil in forum C++ Programming
    Replies: 10
    Last Post: 04-29-2008, 04:29 PM
  4. Concatenating strings (dynamic array using pointers)
    By Tankndozer in forum C Programming
    Replies: 8
    Last Post: 07-01-2004, 07:27 AM
  5. Inputing strings into a dynamic array
    By Nakeerb in forum C++ Programming
    Replies: 1
    Last Post: 10-12-2002, 02:38 AM

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