Thread: malloc, realloc, calloc

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

    malloc, realloc, calloc

    Hi All;

    I am having serious problems getitng the above to work for strings in C, can do it no problem for int*

    here is so some code

    Code:
    #define SIZE 7
    #define STR_SIZE 256
    int main(void)
    {
    	char *array[SIZE];
    	int i;
    
    	for(i=0;i<7;i++)
    	{
    		array[i]=malloc(STR_SIZE);
    		printf("Enter a string:");
    		scanf("%s", array[i]);
    	}
    	
    	for(i=0;i<7;i++)
    		printf("%s\n", array[i]);
            return 0;
    
    	free(array);
    }
    This code is ok, but how would i go about making it more dynamic, saying increasing the array size, i need to use realloc but cant get it working, can some show us?

    Also If i wasnt to use char* array[SIZE] but use char* string how would i do it.


    Please note this is not a homework question but something i am doing to get better at C and cant this working at all.

    Thanks

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    If you want the size to be dynamic, then use a double pointer. Declare your array like:
    Code:
    char **array;
    array = malloc(array_size * sizeof(*array));
    for(i = 0; i < array_size; i++)
    {
        array[i] = malloc(STR_SIZE);
        ...
    bit∙hub [bit-huhb] n. A source and destination for information.

  3. #3
    1337
    Join Date
    Jul 2008
    Posts
    135
    Code:
    int main(void)
    {
    	char *array[7];
    	int i;
    
    	for(i=0;i<7;i++)
    	{
    		array[i]= (char*)malloc(sizeof(array[i])); //cast the malloc to char*
    		printf("Enter a string:");
    		scanf("%s", array[i]);
    	}
    	
    	for(i=0;i<7;i++)
    		printf("%s\n", array[i]);
            return 0;
    
    	free(array);
    }
    Last edited by valthyx; 08-13-2009 at 11:59 AM.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    valthyx: All you added was a cast to malloc() which is a bad practice.
    bit∙hub [bit-huhb] n. A source and destination for information.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    hmm... valthyx, your example seems no better, if not worse: it changes the use of named constants to magic numbers and leaves the call to free() after the return. Casting the retun value of malloc is unnecessary anyway.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    Ok thats good, but the main thing i want to do is jsut use a char *ptr to get dynamically increase when it takes in a string. I have somehting like this:

    Code:
    nt main()
    {
    	int i;
    	char *pdata;
    	int n;
    	printf("Enter number of segments we want");
    	scanf("%d", &i);
    	pdata = calloc(i, sizeof(256));
    	if(pdata==NULL)
    		printf("err");
    
    	for(n=0; n<i;n++)
    	{
    		printf("Enter a name");
    		scanf("%s", &pdata[i]);
    	}
    
    	
    	for(n=0;n<i;n++)
    	{
    		printf("%s\n",pdata[n]);
                    }
    	free(pdata);
    }
    But the print prints out null.
    Trying to create a dynamic pointer of char* to strings, is it possible?


    Thanks

  7. #7
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    sizeof(256) doesn't return what you think it does. sizeof(256) is probably 4.

    I don't see how my original example fails to suit your needs.
    Code:
    nt main()
    {
    	int i;
    	char **pdata;
    	int n;
    	printf("Enter number of segments we want");
    	scanf("%d", &i);
    	pdata = malloc(i * sizeof(*pdata));
    	if(pdata==NULL)
    		printf("err");
    
    	for(n=0; n<i;n++)
    	{
                    pdata[n] = malloc(256);
    		printf("Enter a name");
    		scanf("%s", pdata[n]);
    	}
    
    	
    	for(n=0;n<i;n++)
    	{
    		printf("%s\n",pdata[n]);
                    free(pdata[n]);
            }
    	free(pdata);
    }
    bit∙hub [bit-huhb] n. A source and destination for information.

  8. #8
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    HI;

    Working with your example now, but only one thing else i need to know and maybe you can explain it to me.

    How would i use calloc and realloc in these situations, as i would like to be able increase the **array as i go along. Also after i use realloc or calloc to i need to malloc the array[i] again?

    Thanks

  9. #9
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    You can realloc the array if you need to resize it to something else. If you realloc to make the array bigger, don't forget to call malloc() for each of the new indexes that you have created.
    bit∙hub [bit-huhb] n. A source and destination for information.

  10. #10
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    So something like this

    pdata=realloc(*pdata, sizeof(*pdata));

    which will give one extra onto my array and if i wanted more if be:

    pdata=realloc(*pdata, 4*sizeof(*pdata)); ?


    You totally explain the dynamic stuff to me now, be messing with it for awhile and got half way only.
    Thanks

  11. #11
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    No, that's not right. Your code will shrink pdata down to 1 index and 4 indexes respectively. You would need something like this:

    Code:
    size_t array_size = 10;
    char** pdata;
    
    pdata = malloc(array_size * sizeof(*pdata));
    
    ...
    
    // Now we want to resize pdata from 10 to 15
    array_size = 15;
    pdata = realloc(pdata, array_size * sizeof(*pdata));
    bit∙hub [bit-huhb] n. A source and destination for information.

  12. #12
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    Why does it shrink? Can you explain that?

    Thanks for showing us how to do it.


    Thanks

  13. #13
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    If you call realloc() with a size that is smaller than the size it currently is, then it will shrink. In other words:
    Code:
    int* i = malloc(10 * sizeof(int));
    i = realloc(i, 5 * sizeof(int)); // shrink i from 10 indexes down to 5
    bit∙hub [bit-huhb] n. A source and destination for information.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    If you want to be really careful, assign the result of realloc() to another pointer instead of pdata. If the return value of realloc is not a null pointer, then assign that auxiliary pointer's value to pdata. This ensures that if realloc was not able to allocate space, you still have a pointer to the already allocated array's first element.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Aug 2009
    Posts
    58
    Hi Guys;

    Thanks a mill, totally misunderstood how realloc worked and it was killing me!

    I thought it added on to the current load!

    Here is my code now:
    Code:
    int main()
    {
    	int i;
    	char **pdata;
    	//pdata = malloc(1 * sizeof(*pdata));
            pdata=calloc(4, sizeof(*pdata));
    
    	for(i=0;i<4;i++)
    	{
    		printf("Enter a name");
    	        pdata[i] = malloc(STR_SIZE);
    		scanf("%s", pdata[i]);
    	}
    
    	pdata=realloc(pdata, 5*sizeof(*pdata));
    
    	pdata[4]=malloc(STR_SIZE);
    	printf("Enter a string");
    	scanf("%s", pdata[4]);
    
    	for(i=0;i<5;i++)
    	{
    	     printf("\n%s", pdata[i]);
    	     free(pdata[i]);
    	}
    }


    Thanks again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Difference BW malloc() and calloc() and realloc()
    By svelmca in forum C Programming
    Replies: 2
    Last Post: 03-31-2009, 05:59 AM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. malloc, realloc
    By figo2476 in forum C Programming
    Replies: 3
    Last Post: 04-28-2006, 10:11 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc and realloc
    By odysseus.lost in forum C Programming
    Replies: 3
    Last Post: 05-27-2005, 08:44 AM