malloc and calloc

This is a discussion on malloc and calloc within the C Programming forums, part of the General Programming Boards category; Would someone explain to me how to use these? I keep getting a segmentation fault on this line: Code: strcpy(lines[e++] ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    36

    malloc and calloc

    Would someone explain to me how to use these? I keep getting a segmentation fault on this line:

    Code:
    strcpy(lines[e++] = calloc(l + 1, l + 1), storeline);
    lines is a pointer array, storeline is a character string, l is the length of storeline, and my whole calloc expression is a pointer to space of the same size as storeline(at least that's what I'm going for).

    As I understand it right now, the first parameter of calloc is the number of elements in an array(storeline) and the second parameter is the number of bytes of the memory block which is the same since 1 char = 1 byte?

    If someone would show me how to use these functions I'd really appreciate it. Thanks.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    The first is the number of members, and the second is the size of one member.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    Let me simplify and correct that for you:
    Code:
    lines[e] = calloc(l + 1, 1);
    strcpy(lines[e++], storeline);
    Those lines of code should only give you a seg fault if:
    1. lines is not a valid memory address
    2. e is out of bounds
    3. storeline is not a valid memory address
    4. you've already corrupted the heap
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    Feb 2009
    Posts
    36
    Thank you both.

    I'm still getting a segmentation fault. This time in the strcpy line.

    Code:
    	while (l = getline(storeline, MAXLEN))
    	{
    		lines[e] = calloc(l + 1, 1);
    		strcpy(lines[e++], storeline);
    	}
    This block is at the top of my program. The only thing above it is some error checking for argv. e is initialized at zero and here are my arrays:

    Code:
    	char *lines[MAXLINES];
    	char storeline[MAXLEN];
    Thanks again.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Does e go past MAXLINES? And is getline your own creation, since it doesn't seem to be the GNU version? If so, does it properly null-terminate things?

  6. #6
    Registered User
    Join Date
    Feb 2009
    Posts
    36
    Yeah that's my version of getline and it does terminate the string. e does go past MAXLINES though.

    Program received signal SIGSEGV, Segmentation fault.
    0x08048648 in main (argc=2, argv=0xbffff4f4) at exercise.5-13.c:56
    56 strcpy(lines[e++], storeline);
    (gdb) print e
    $1 = 134556832

  7. #7
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    For safety, you might want to declare your loop like this:
    Code:
    while ((e < MAXLINES) && (l = getline(storeline, MAXLEN)))
    bit∙hub [bit-huhb] n. A source and destination for information.

  8. #8
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,308
    Quote Originally Posted by rrc55 View Post
    e does go past MAXLINES though.
    Oh great, so you found the problem!
    A more useful way to fix it would be to make lines a char** and allocate the array of char*'s dynamically. Then when you run out of empty char*s in the array you can malloc an array twice as big and copy the old char*'s across. Basically simulating a C++ vector.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  9. #9
    Registered User
    Join Date
    Feb 2009
    Posts
    36
    Yeah thanks guys. So it turns out my getline function was returning length + 1 the whole time so my while loop never finished and that's why e was so high. For now I just removed the "+ 1" from my calloc expression and it worked like a charm. But now I can't for the life of me figure out why my getline function seems to be counting 1 more than it's supposed to. I'm sure it's something very simple and I'm just too much of a noob to see it but I bet you guys will see it quickly! Here it is:

    Code:
    int getline(char *s, int lim)
    {
        int i = 0;
        
        for (s; --lim > 0 && (*s=getchar()) != EOF && *s != '\n'; ++s)
            ++i;
    
        if (*s == '\n')
    	++i;
        ++s;
        *s = '\0';
        return i;
    }

  10. #10
    Registered User
    Join Date
    Feb 2009
    Posts
    36

    Unhappy

    Spoke to soon. I tested the first line out of the loop and it worked. When I use the loop without the "+ 1" in the calloc parameter I still get a segmentation fault in my strcpy line. I'll get back to you.

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by rrc55 View Post
    Spoke to soon. I tested the first line out of the loop and it worked. When I use the loop without the "+ 1" in the calloc parameter I still get a segmentation fault in my strcpy line. I'll get back to you.
    Probably because strcpy() appends a '\0', and you did not count that in getline(). It is normal, for example, to use strlen(s)+1 in a malloc() call since strlen() will not count the '\0' either.
    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

  12. #12
    Registered User
    Join Date
    Feb 2009
    Posts
    36
    Wow silly me. Of course it doesn't work in the loop because the loop still doesnt end.

    ***

    Although I still don't get why getline was counting 1 more the length I wanted, it was an easy fix. Now the loop ends but I still get a segmentation fault. I did a little test and ran a loop that copied every line into lines[e] and then printed the string lines[e]. That loop worked just fine. It's just when I try to increment e and build my pointer array that everything seems to break down.
    Last edited by rrc55; 09-02-2009 at 11:00 AM.

  13. #13
    Registered User
    Join Date
    Feb 2009
    Posts
    36
    Quote Originally Posted by MK27 View Post
    Probably because strcpy() appends a '\0', and you did not count that in getline(). It is normal, for example, to use strlen(s)+1 in a malloc() call since strlen() will not count the '\0' either.
    Thank you but I ahve already accounted for this.

  14. #14
    Registered User
    Join Date
    Feb 2009
    Posts
    36
    Turns out my input file had more lines than my MAXLINES. Can't believe I overlooked especially considering someone tried to point that out to me! Anyway, sorry for the confusion and thanks for the help.

  15. #15
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by rrc55 View Post
    Wow silly me. Of course it doesn't work in the loop because the loop still doesnt end.

    ***

    Although I still don't get why getline was counting 1 more the length I wanted, it was an easy fix. Now the loop ends but I still get a segmentation fault. I did a little test and ran a loop that copied every line into lines[e] and then printed the string lines[e]. That loop worked just fine. It's just when I try to increment e and build my pointer array that everything seems to break down.
    So now I have two key topics on my "to do" tutorial:
    1. How to test a premise in C
    2. How to avoid "Stream of Consciousness" commentary


    Just kidding rrc55, I'm glad things worked out for you.
    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

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc, calloc from the FAQ
    By salvadoravi in forum C Programming
    Replies: 10
    Last Post: 01-21-2008, 03:29 AM
  2. Malloc & Calloc difference in terms of memory allocated
    By swapnaoe in forum C Programming
    Replies: 2
    Last Post: 04-19-2007, 01:57 AM
  3. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 06:37 AM
  4. difference between calloc and malloc
    By saravanan_ts in forum C Programming
    Replies: 4
    Last Post: 07-28-2003, 07:13 AM

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