Find the answer to your Linux question:
Results 1 to 4 of 4
In C: Is: Code: array = (char **)calloc(nelem, sizeof(char *) equivalent to: Code: array = (char **)malloc(nelem*sizeof(char *)) I'm getting seg faults. I want to find a way to realloc ...
  1. #1
    Linux Newbie
    Join Date
    Feb 2006
    Location
    Dover, DE
    Posts
    112

    calloc and malloc question

    In C:
    Is:
    Code:
    array = (char **)calloc(nelem, sizeof(char *)
    equivalent to:
    Code:
    array = (char **)malloc(nelem*sizeof(char *))
    I'm getting seg faults. I want to find a way to realloc array. (change it's size on the fly)

  2. #2
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    You can resize a previously allocated memory block with the realloc() function.
    The function resizes memory previously obtained with a malloc() or calloc().
    Try this (assuming that array is a pointer returned by malloc or calloc):

    Code:
    array = realloc(array, nelem*sizeof(char));
    Regards

  3. #3
    Linux Newbie
    Join Date
    Feb 2006
    Location
    Dover, DE
    Posts
    112
    That is what I am doing.
    I allocated memory like this:
    Code:
    array = (char **)calloc(nelem, sizeof(char *))
    but when my nelem changes and I do
    Code:
    array = (char **)realloc(nelem*sizeof(char *))
    I get a segmentation fault after a few reallocations.
    Should this work or is there something else I'm doing wrong?

  4. #4
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    Here's an example how to allocate and reallocate memory for an array of strings:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main ()
    {
        char **words;
        int i;
    
        words = malloc(10*sizeof(char*)); // allocate 10 pointers to array of string
        
        for( i = 0; i < 10; i++ ) {		// allocate memory for 25 chars for each string
    	words[i] = malloc(25);
    	sprintf(words[i], "&#37;s","abc");
    	printf("%s\n", words[i]);
        }
        
        words = realloc(words, 11*sizeof(char*));	// reallocate a pointer to an array of string
        words[10] = malloc(25);			// reallocate memory for 25 chars for the string
        sprintf(words[10], "%s","efg");		//+of the 11th element
        printf("%s\n", words[10]);
    
        for( i = 0; i < 11; i++ ) {
          free(words[i]);
        }
        free(words);
    }

    Regards

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...