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 ...
- 06-09-2007 #1Linux Newbie
- Join Date
- Feb 2006
- Location
- Dover, DE
- Posts
- 112
calloc and malloc question
In C:
Is:equivalent to:Code:array = (char **)calloc(nelem, sizeof(char *)
I'm getting seg faults. I want to find a way to realloc array. (change it's size on the fly)Code:array = (char **)malloc(nelem*sizeof(char *))
- 06-09-2007 #2Linux 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):
RegardsCode:array = realloc(array, nelem*sizeof(char));
- 06-09-2007 #3Linux Newbie
- Join Date
- Feb 2006
- Location
- Dover, DE
- Posts
- 112
That is what I am doing.
I allocated memory like this:
but when my nelem changes and I doCode:array = (char **)calloc(nelem, sizeof(char *))
I get a segmentation fault after a few reallocations.Code:array = (char **)realloc(nelem*sizeof(char *))
Should this work or is there something else I'm doing wrong?
- 06-10-2007 #4Linux 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], "%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


Reply With Quote