Thread: malloc? What is this?

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    91

    malloc? What is this?

    What is malloc? I've been wondering about this on thursday, did some online reading, told me about how it makes size of memory so you can use it outside the function or something like that. If anyone has time on their hands , can you guys explain this to me and how it will be used in a code... cause I have no idea what this is, but it seems important.

    Thank you.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    You can find a discussion of malloc and the data type it returns at our fine web site. http://www.cprogramming.com/tutorial/c/lesson6.html

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    91
    Quote Originally Posted by citizen View Post
    You can find a discussion of malloc and the data type it returns at our fine web site. http://www.cprogramming.com/tutorial/c/lesson6.html
    Thanks for the quick response, and thanks for the link. I'll check it out, see if I can do it on my own, but I need help, I'll post it here Thanks you guys ^^. Very grateful

  4. #4
    Registered User
    Join Date
    Oct 2008
    Posts
    91
    Okay, so I've been trying but I can't seem to get it working.
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    char *ra(int howMany, int start, char *c);
    
    int main(void) {
    	char str1[] = "C programming is awesome";
    	char *c = ra(7, 2, str1);
    	printf("RA RETURNED: &#37;s of %s\n", c, str1);
    
    	return EXIT_SUCCESS;
    }
    
    char *ra(int many, int st, char *c){
    	int *ra = malloc(c * sizeof (int);
    	return(st);
    }
    I know there is something definitely wrong, and I asked a few friends and they haven't done malloc yet so... lol. My main goal is so that the function mallocs space for a new string with the amount of "many" chars plus the null char. Then somehow copy the string starting at the "st" index. Also is there a way where i can copy "many" chars, and end the string with the null char. Another thing I've been thinking about is, if its possible to return a pointer to this new string... that is if its possible..

    can anyone just guide me and point me in the right direction , any help will be appreciated
    Last edited by dlwlsdn; 11-08-2008 at 03:26 PM. Reason: was *bar, its now *ra.. Thanks for letting me know, but I tried it, didn't work. :'(...

  5. #5
    Registered User Phoenix_Rebirth's Avatar
    Join Date
    Dec 2005
    Location
    Cyprus
    Posts
    68
    well first of all the function is declared bar but then is called as ra
    Also malloc returns a pointer (void I think) and you assign the result in the function ra to an int*. The you return a pointer to an integer when your function returns a poiter to char. Also you allocate space for integers instead of char which is what you want

    if you want to allocate memory for a string for "many" characters then you have to do something like this

    char *p = malloc( (int many) * sizeof(char) )

    This returns a char pointer to the head/start of a string (or an array of char if you prefer) with size "many"
    If "many" = 5 Then char *p = malloc( 5 * sizeof(char) ) and p points to an array of 5 spaces.

    char *p = malloc( 5 * sizeof(char) ) is equal to char p[5];

    Furthermore if you want to include the finishing null character then change "many" to "many"+1
    Last edited by Phoenix_Rebirth; 11-08-2008 at 03:33 PM.

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Well, you're rather confused, I think. You're using the wrong variable in several places; you're allocating a multiple of sizeof(int) rather than of char. You're using int* instead of char*. Your code has several typos which makes me think you typed it from memory (or something) rather than copy-pasting it, which is never a good idea. (Your prototype says "bar", not "ar", and you're missing a closing parenthesis.)

    And you're using such short variable names that it can't be helping you figure things out.

    It's quite simple, really.
    • Calculate how much memory you need. This will likely be the length of the string you want to copy, plus one for a NULL char.
    • Allocate that much memory, and store it in a char* pointer!
    • Copy your substring to this new memory.
    • Return your new string.


    Perhaps you're thinking of something like this.
    Code:
    char *extract_substring(char *string, int start, int length) {
        char *new_str = malloc(length - start + 1);
        strcpy(new_str, string + start);
        return new_str;
    }
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    91

    Talking

    Quote Originally Posted by dwks View Post
    Well, you're rather confused, I think. You're using the wrong variable in several places; you're allocating a multiple of sizeof(int) rather than of char. You're using int* instead of char*. Your code has several typos which makes me think you typed it from memory (or something) rather than copy-pasting it, which is never a good idea. (Your prototype says "bar", not "ar", and you're missing a closing parenthesis.)

    And you're using such short variable names that it can't be helping you figure things out.

    It's quite simple, really.
    • Calculate how much memory you need. This will likely be the length of the string you want to copy, plus one for a NULL char.
    • Allocate that much memory, and store it in a char* pointer!
    • Copy your substring to this new memory.
    • Return your new string.


    Perhaps you're thinking of something like this.
    Code:
    char *extract_substring(char *string, int start, int length) {
        char *new_str = malloc(length - start + 1);
        strcpy(new_str, string + start);
        return new_str;
    }
    Let me see if I understand what you wrote...

    Code:
    char *extract_substring(char *string, int start, int length)
    - Means you want "extract_substring" to be a pointer to a char.
    - The function of "extract_substring" has a pointer named "string" pointing to a char, has a int called "start", and also a int called "length".

    Code:
    char *new_str = malloc(length - start + 1);
    - A new pointer called "new_str" (which we want it to be a new string later on), is a pointer to a char.
    - The pointer called "new_str" also has malloc(length - start + 1);, which is how much space we want to allocate. And the amount of memory we want to allocate is (the length of the string) - (the starting index given) + (NULL termination so '\0' or 0)

    Code:
        strcpy(new_str, string + start);  
             return new_str;
    - In this part we are copying the string with "strcpy" and we are copying the "new_str". I don't quite understand the part of "string + start.
    - Then finally we want to return the "new_str" like I wanted...


    can you tell me if I'm somewhat on the right track reading this. Thanks for helping me out. really appreciate it

  8. #8
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I think a more correct line-by-line dissection would be (slight edits to dwks' example)

    Code:
    1: char * 
    2: extract_substring ( char * str, int start, int length )
    3: {
    4:    char * new_str = malloc( length - start + 1 );
    5:    strncpy( new_str, str + start, length );
    6:    new_str[length] = '\0';
    7:    return new_str;
    8: }
    1. The function's return value - you know that this will return a string.

    2. On this line is the name of our function, which explains what it does, and the parameters required to do it. We have the original string named str, a starting location named start and a length of characters to copy. All of these parameters have data types.

    4. We call malloc on this line. As you should have learned from the tutorial, malloc returns at least the amount of its argument (a size) in bytes.

    5. The example uses pointer arithmetic to start copying at the appropriate index. Without going into a lesson, it's as if we moved str by start characters and stored the value in strncpy's source argument. But this does not affect the value stored in str. We could have accomplished the same with the syntax &str[start] - what you use is up to you.

    Going into a lesson, treat pointers like a ruler when you do arithmetic with pointer variables. Addition and subtraction is like moving up and down a number line, and you can imagine the stored address moving up and down n-bytes. When you store this calculated amount (assignment) think of it like marking a spot on a ruler.

    For larger data than a char, you will have to multiply by the size of the object to get the difference in addresses, but that's really low level thinking. You're almost never concerned with the size of things as much as how many elements you skipped over in the array.

    The copy happens and we move on to line six.

    6. This terminates the string by storing a zero at that index.

    7. Then you return the string desired and the function is done.
    Last edited by whiteflags; 11-08-2008 at 04:19 PM. Reason: spelling corrections

  9. #9
    Registered User
    Join Date
    Oct 2008
    Posts
    91
    Quote Originally Posted by citizen View Post
    I think a more correct line-by-line dissection would be (slight edits to dwks' example)

    Code:
    1: char * 
    2: extract_substring ( char * str, int start, int length )
    3: {
    4:    char * new_str = malloc( length - start + 1 );
    5:    strncpy( new_str, str + start, length );
    6:    new_str[length] = '\0';
    7:    return new_str;
    8: }
    1. The function's return value - you know that this will return a string.

    2. On this line is the name of our function, which explains what it does, and the parameters required to do it. We have the original string named str, a starting location named start and a length of characters to copy. All of these parameters have data types.

    4. We call malloc on this line. As you should have learned from the tutorial, malloc returns at least the amount of its argument (a size) in bytes.

    5. The example uses pointer arithmetic to start copying at the appropriate index. Without going into a lesson, it's as if we moved str by start characters and stored the value in strncpy's source argument. But this does not affect the value stored in str. We could have accomplished the same with the syntac &str[start] - what you use is up to you.

    Going into a lesson, treat pointers like a ruler when you do arithmetic with pointer variables. Additiion and subtraction is like moving up and down a number line, and you can imagine the stored address moving up and down n-bytes. When you store this calculated amount (assignment) think of it like marking a spot on a ruler.

    For larger data than a char, you will have to multiply by the size of the object to get the difference in addresses, but that's really low level thinking. You're almost never concerned with the size of things as much as how many elements you skipped over in the array.

    The copy happens and we move on to line six.

    6. This terminates the string by storing a zero at that index.

    7. Then you return the string desired and the function is done.
    YOU GUYS ARE SO SMART AND SO GODLY!!!!! , I FULLY UNDERSTAND THIS!!!

    but can't we write like what "pheonix_rebirth" wrote? something char *p = malloc( (many + 1) * sizeof(char))

    and do something like this?

    but you guys are truly godly, i will see if this works and stuff... Coding is lots of work, but its soo fun . Thanks guys, I really appreciate it.

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    >> but can't we write like what "pheonix_rebirth" wrote? something char *p = malloc( (many + 1) * sizeof(char))

    You can write that, but sizeof (char) is always 1. More generally, the size of things will be important, as you need say 20 bytes for five integers. This was covered in the tutorial I think.

  11. #11
    Registered User
    Join Date
    Oct 2008
    Posts
    91
    Quote Originally Posted by citizen View Post
    >> but can't we write like what "pheonix_rebirth" wrote? something char *p = malloc( (many + 1) * sizeof(char))

    You can write that, but sizeof (char) is always 1. More generally, the size of things will be important, as you need say 20 bytes for five integers. This was covered in the tutorial I think.
    yeah, it was covered, and char is 1 byte right and integer is 4? Or something like that.... but I was just wondering if there was another way to write this with malloc.

  12. #12
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    you mean
    Code:
    char * new_str = malloc( (length - start + 1)*sizeof(char) );
    ?
    Sure.

    4 bytes for int isn't guaranteed, but is usually the case on modern PCs with modern compilers.

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > but I was just wondering if there was another way to write this with malloc.
    The FAQ on using malloc goes into it...
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. the basics of malloc
    By nakedBallerina in forum C Programming
    Replies: 21
    Last Post: 05-20-2008, 02:32 AM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM