Like Tree1Likes
  • 1 Post By Nominal Animal

Realloc Segmentation Fault

This is a discussion on Realloc Segmentation Fault within the C Programming forums, part of the General Programming Boards category; Hi everyone, I am practicing the use of realloc() in a practice function so that I will be able to ...

  1. #1
    Registered User
    Join Date
    Oct 2012
    Posts
    71

    Realloc Segmentation Fault

    Hi everyone,

    I am practicing the use of realloc() in a practice function so that I will be able to use it in my real program. The aim for me right now is to concatenate 2 strings but I continue to get segmentation fault from extending the memory allocated to the first string, which should be needed for making it longer through concatenation. Here is my code, thanks for all the help!

    Any comments, suggestions, advice to improve coding ability are greatly appreciated!

    Code:
    #include <stdio.h>
    #include <malloc.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(int argc, char **argv) {
    
      char *in;
      char *im;
      im="/0\0";
      in="/5\0";
      printf("in=%s im=%s in=%d im=%d\n len(in+im)=%d",in,im,strlen(in),strlen(im),strlen(im)+strlen(in));
        in=realloc(in,strlen(in)+strlen(im)+1);
      //  strcat(in,im);
      printf("in=%s\n",in);
    }

  2. #2
    Registered User
    Join Date
    Oct 2011
    Posts
    872
    Here,
    Quote Originally Posted by workisnotfun View Post
    Code:
      im="/0\0";
      in="/5\0";
    you set the two pointers to point to static constants. You cannot reallocate such pointers.

    You can only reallocate NULL (in which it is the same as malloc()), or a previously dynamically allocated pointer.

  3. #3
    Registered User
    Join Date
    Oct 2012
    Posts
    71
    Would allocating memory to the pointers, then assigning characters to them be a good solutions?

    I try

    char *in=malloc(3);
    char *im=malloc(3);

    at the start but still no good.

  4. #4
    Registered User
    Join Date
    Oct 2011
    Posts
    872
    Quote Originally Posted by workisnotfun View Post
    Would allocating memory to the pointers, then assigning those values to it be a good solutions?
    Something like the following?
    Code:
        static const char original[] = "Something";
        char *string;
        size_t length;
    
        /* We need length + 1 characters. */
        length = strlen(original);
        string = malloc(length + 1);
        if (!string) {
            fprintf(stderr, "Out of memory.\n");
            return 1;
        }
    
        /* Initialize the string. We know string is long enough. */
        strcpy(string, original);
    Or, if you have POSIX.1-2008 support,
    Code:
    #define _POSIX_C_SOURCE 200809L
    
        char *string;
    
        string = strdup("Something");
        if (!string) {
            fprintf(stderr, "Out of memory.\n");
            return 1;
        }
    both will give you a dynamically allocated pointer, to a string "Something", you can reallocate.

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    872
    Quote Originally Posted by workisnotfun View Post
    I try
    Code:
      char *in=malloc(3);
      char *im=malloc(3);
    You need to also check for NULL (well, those are not going to fail, but it is good form), but more importantly, initialize them to something. For example, to an empty string:
    Code:
        *in = '\0';
        *im = '\0';
    or to any two-character or shorter string -- remember, the '\0' that ends the string requires one char:
    Code:
        strcpy(in, "in");
        strcpy(im, "im");

  6. #6
    Registered User
    Join Date
    Oct 2012
    Posts
    71
    I think I get it now. So if you want to move values to a char* that you know will later be modified in length(adding or subtracting characters to the string), then the key is to use strcpy( string , "Words" ) and also to allocate memory to it beforehand. I've pretty much incorporated both of your suggestions and my practice code is working fine now! Thanks for all the help Nominal!

  7. #7
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    A general comment about realloc.It does not target this code,so you may skip it if you like.

    Consider you have an array and you want to increase it's capacity with realloc.Never increase it's capacity with a constant number of cells.Always increase it by a percentage term.Even doubling it is 100% increment.In first case complexity approaches O(nē), where in second case it remains O(n).

  8. #8
    Registered User
    Join Date
    Oct 2011
    Posts
    872
    Quote Originally Posted by std10093 View Post
    Never increase it's capacity with a constant number of cells.Always increase it by a percentage term.
    Well, that's completely bonkers.

    There are only two factors to consider, and both are domain-specific:
    1. How often is realloc() called for each item
    2. How much memory is wasted by memory allocated, but not used

    If you always double your allocation size, you basically wish to minimize the number of realloc() calls, while accepting that up to half of the memory allocated may end up unused. (I think it averages to a quarter allocated but unused, if sizes are completely random. I'm too lazy to check.)

    The best strategy depends on the domain, but I've found the following to be a good guideline:
    1. When size is small, use a small fixed size increase
    2. When size is very large, use a large fixed size increase
    3. In between, increase the size by a factor

    For example, for sizes less than say 256 bytes you always grow by 16 bytes. Above say 4194304 bytes you grow by 1048576 bytes (1 M). Between, you grow by say 1/4. This strategy means that on average, you only have about 8 unused but allocated bytes for short items, and about 12.5% for medium-length items; and no more than 1048576 unused but allocated bytes per any item.

    But, that's just one example of a viable strategy. If you happen to know the probability distribution for the length of your items, using that you can optimize the number of realloc() calls and still avoid having a lot of allocated but unused memory.
    Matticus likes this.

  9. #9
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Nomimal,the point is to increase by a percentage term,not double it( i mean it is not a must)!

    bonkers <- that is a word i do not know ,nor me nor google translate.Anyway

  10. #10
    Registered User
    Join Date
    May 2009
    Posts
    2,747
    Quote Originally Posted by std10093 View Post
    bonkers <- that is a word i do not know ,nor me nor google translate.Anyway
    It ("bonkers") means something like crazy.

    Tim S.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  11. #11
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by stahta01 View Post
    It ("bonkers") means something like crazy.

    Tim S.
    wordsKnownBySam++;

    thanks Tim

  12. #12
    Registered User
    Join Date
    Oct 2011
    Posts
    872
    Quote Originally Posted by std10093 View Post
    Nomimal,the point is to increase by a percentage term,not double it( i mean it is not a must)!
    And I meant it was irrational to increase by fraction (a percentage term) for either very small allocations, or very large allocations, because a fixed size increase works better for those.

    I used "bonkers", because I thought it was a bit softer than "crazy" or "irrational", closer to "ill-advised". English is not my native language either, so I often get the nuances completely bonkers myself.

    No offense intended.

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,159
    Quote Originally Posted by Nominal Animal
    And I meant it was irrational to increase by fraction (a percentage term) for either very small allocations, or very large allocations, because a fixed size increase works better for those.
    More accurately, I think that you meant that it is irrational to insist that the capacity never be increased by a fixed size since in some situations increasing by a fixed size can be closer to optimal -- with respect to number of allocations and space wastage -- than increasing by a fraction/percentage term.
    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

  14. #14
    Registered User
    Join Date
    Oct 2011
    Posts
    872
    Quote Originally Posted by laserlight View Post
    More accurately, I think that you meant that it is irrational to insist that the capacity never be increased by a fixed size since in some situations increasing by a fixed size can be closer to optimal -- with respect to number of allocations and space wastage -- than increasing by a fraction/percentage term.
    Heh, you're absolutely right. Fractional size increase works quite well for intermediate-size reallocations; it was the bold "never fixed size increase" I had issue with.

    But most importantly, the best reallocation strategy does depend on the use case. After all, the intent is to keep both unused but allocated memory, and the number of realloc() calls, as small as possible.

    With many data structures you can reallocate to the required size exactly, because reallocations (changes in size) are rare. In particular, if you are in the process of creating a string or array -- say reading its contents from a file --, you might use more greedy approach than if you were just appending to an existing one; and when complete, reallocate to the exact desired size. That way you could have different strategies for creation and modification.

    Memory management is a very complex topic even for relatively normal applications. I particularly like the approach Apache has: it constructs pools of allocations, so that individual allocations do not need to be tracked, as the entire pool is released at once. Typically, each page request will have their own pool, although internal functions sometimes create temporary pools too. If I did my own implementation, each "pool" would actually be a chain, and reallocations would first look for room in all nodes in the same chain. Then, multiple factors would affect the selection: if a specific choice lets me free a complete node, then that is a very good one. If there is one that has a suitably sized hole, I should use that, so that a longer allocation has better chance of finding free space, instead of having to allocate a new pool node. And so on. Any rule of the size to reallocate to should then consider my pool allocation strategies too, so that they do not end up fighting each other.

    Similarly, if you have a tree data structure with lots of elements, you could maintain an array of the nodes and use indices instead of pointers. In normal operation, you rarely need to use memory management. If you have single links, you can easily compact the tree. Then, the reallocation strategy is more along the lines "Ouch, no free elements. Would it be worth compacting the tree now, or would it be better to reallocate some more elements and compact later on?", compaction being about the same complexity as a full traversal of the tree.

    Argh. I'm sorry. I'm writing a novel again.

  15. #15
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by Nominal Animal View Post
    Argh. I'm sorry. I'm writing a novel again.
    Some users,like me might find that novel interesting enough
    Laserlight and you might be right.The word always is very weighty to use.Especially for a guy like me,who has soooo much to learn yet!!!!!!I mean i feel like i know a topic well enough and as the flow of lige goes on issues are going to be poped-up which i do not fully understand them.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. segmentation fault
    By muppy in forum C Programming
    Replies: 10
    Last Post: 06-05-2011, 06:28 PM
  2. Help with segmentation fault!!!
    By Tiago Ferreira in forum C Programming
    Replies: 3
    Last Post: 05-31-2011, 08:34 AM
  3. Unknown Seg Fault and Malloc/Realloc Problems
    By DonFord81 in forum C Programming
    Replies: 6
    Last Post: 12-01-2008, 11:49 PM
  4. segmentation fault when using gcc
    By stodd04 in forum C Programming
    Replies: 6
    Last Post: 02-14-2005, 07:34 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM

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