Thread: malloc () function troubles.

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #4
    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.
    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

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, 04: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, 05:51 PM

Tags for this Thread