Like Tree5Likes
  • 1 Post By DRK
  • 2 Post By MK27
  • 1 Post By claudiu
  • 1 Post By hk_mp5kpdw

malloc () function troubles.

This is a discussion on malloc () function troubles. within the C Programming forums, part of the General Programming Boards category; guys, I made this program and I would like to have your opinion and suggestions if this is correct; I ...

  1. #1
    Registered User
    Join Date
    Apr 2012
    Location
    Olongapo City, Philippines, Philippines
    Posts
    3

    malloc () function troubles.

    guys,

    I made this program and I would like to have your opinion and suggestions if this is correct; I having trouble with malloc (), the objective here is I need to allocate enough memory for the variable newstring after it was concatenated using strcat function and I have no idea how to check if my malloc() was allocated the space for the variable newstring.

    Code:
    /* This will use malloc() function to allocate */
    /* memory for the concatenated two strings */
    
    
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    char *conca_str(char *, char *);
    
    
    int main( void )
    {
    
    
        char *str1 = "Hello";
        char *str2 = " World!";
        char *join;
    
    
        join = conca_str(str1, str2);
        
        printf("%s\n", join);
    
    
        free(join);
    
    
        return 0;
    }
    
    
    char *conca_str(char *string1, char *string2)
    {
        char *conca, *newstring;
        
        newstring = strcat(string1, string2);
    
    
        conca = (char *) malloc (100);
        
        conca = newstring;
    
    
        return conca;
    }
    Appreciate your positive response.

    Regards,
    pvrgallardo

  2. #2
    DRK
    DRK is offline
    Registered User
    Join Date
    Jun 2009
    Posts
    108
    Code:
    char *conca_str(const char *string1, const char *string2)
    {
        char *conca;
        conca = malloc(strlen(string1) + strlen(string2) + 1);
        strcpy(conca, string1);
        strcat(conca, string2);
        return conca;
    }
    pvrgallardo likes this.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    There's a few things you don't understand here.

    Strings are mutable in C, and while strcat() does return a pointer to the "new" string, it also adds a to b:

    Code:
    char a[256] = "hello ",
        b[] = "world";
    
    strcat(a, b);
    
    puts(a);
    'a' is now "hello world". Notice that I was careful to make sure there is enough space in a to include the addition.

    There is a subtle difference between a regular char array and a string literal:

    Code:
    char *pointerToLiteral = "string literal";
    char arrayString[] = "string in array";
    The first one is declared as a pointer, but what it points to is a string literal. String literals are not mutable. The pointer itself can be reassigned, but you cannot change the literal it currently points to.

    Ie, you cannot use either of these:

    Code:
        char *str1 = "Hello";
        char *str2 = " World!";
    As the first argument to strcat().

    WRT to malloc(), it assigns an address with whatever amount of memory attached. When you do this:

    Code:
        conca = (char *) malloc (100);
    
        conca = newstring;
    You throw that memory away (ie, leak it) by reassigning the pointer to some other address (the return value from the previous strcat). That memory is still allocated, but you can never do anything with it again because you have no way to access it (hence, leaked).
    Last edited by MK27; 04-17-2012 at 12:31 AM.
    camel-man and pvrgallardo like this.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Apr 2012
    Location
    Olongapo City, Philippines, Philippines
    Posts
    3
    thank you DRK, but I have another question, so I cannot do malloc() function after the string was concatenated? Because from what I understand from your given correction is that you allocate memory space before the string was concatenated.

    What I'm trying to do is to concatenate the two strings and allocate space for the new string and then return a pointer to this new string, see below what I did;

    Code:
    char *conca_str(const char *string1, const char *string2){
    	char *newstr= strcat(string1, string2);
     	
    	char *conca = (char *) malloc (strlen(newstr)+1);
    
    
    	strcpy(conca,newstr);
    
    
    	return conca;
    }
    Appreciate your positive comment.

  5. #5
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    If you do that you need to ensure that string1 has enough space to append string2 at the end of it.

    A better way would be to allocate memory in newstr for string1, string2 + 1 (for \0), then strcpy string1 into it and finally strcat string2. That way steer clear of affecting the integrity of your parameters (although there is no danger of that in this case).

    Don't cast the return value of malloc, and make sure you free what you return from this function in the calling function, or else you will be leaking memory.
    pvrgallardo likes this.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  6. #6
    Registered User
    Join Date
    Apr 2012
    Location
    Olongapo City, Philippines, Philippines
    Posts
    3
    merci claudiu, actually here is my created program;
    Code:
    * This will use malloc() function to allocate *//* memory for the concatenated two strings */
    
    
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    char *conca_str(char *, char *);
    
    
    int main( void )
    {
    
    
    	char str1[256] = "Hello";
    	char str2[256] = " World!";
    	char *join;
    
    
    	join = conca_str(str1, str2);
    	
    	printf("%s\n", join);
    
    
    	free(join);
    
    
    	return 0;
    }
    
    
    char *conca_str(char *string1, char *string2)
    {
    	char *newstr= strcat(string1, string2);
     	
    	char *conca = (char *) malloc (strlen(newstr)+1);
    
    
    	strcpy(conca,newstr);
    
    
    	return conca;
    }
    does it look ok?

  7. #7
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,799
    Quote Originally Posted by MK27 View Post
    Ie, you cannot use either of these:

    Code:
    	
    char *str1 = "Hello";
    char *str2 = " World!";
    As the first argument to strcat().
    Cases like this would normally be caught at compile time if the programmer recognizes them as string literals and puts the appropriate const qualifier in place:
    Code:
    const char *str1 = "Hello";
    const char *str2 = " World!";
    Done this way, they'd get a compile time error using either str1 or str2 as the first argument to strcpy/strcat and they'd know (hopefully) to fix the problem. Without the const in place however a user would not know anything was wrong until they ran the program. For beginners unused to the intricacies of the language such issues can be perplexing.
    MK27 likes this.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc function
    By roaan in forum C Programming
    Replies: 9
    Last Post: 08-14-2009, 04:48 AM
  2. Function and pointer troubles
    By ulillillia in forum C Programming
    Replies: 7
    Last Post: 04-25-2009, 04:25 PM
  3. function troubles again
    By wwwildbill in forum C Programming
    Replies: 3
    Last Post: 02-22-2009, 03:27 PM
  4. OpenPrinter function call troubles
    By stanlvw in forum Windows Programming
    Replies: 0
    Last Post: 06-05-2008, 04:23 PM
  5. Array/Function Troubles
    By Astra in forum C Programming
    Replies: 18
    Last Post: 11-16-2006, 04:51 PM

Tags for this Thread


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