allocate memory in subfunctions?

This is a discussion on allocate memory in subfunctions? within the C Programming forums, part of the General Programming Boards category; i don't understand the difference here: Code: #include <stdio.h> #include <stdlib.h> #include <string.h> char *blah; void getmem() { blah = ...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    5

    allocate memory in subfunctions?

    i don't understand the difference here:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char *blah;
    
    void getmem()
    {
          blah = malloc(10);
    }
    
    int main()
    {
          char buffer[10];
    
          getmem();
          fgets(buffer, sizeof buffer, stdin);
          strcpy(blah, buffer);
          puts(blah);
          return 0;
    }
    in the above case the memory is apparently allocated inside getmem, then disappears once getmem returns, but in the below case...

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct ex {
          char *ptr_1;
    } whatever;
    
    void getmem(struct ex *ptr)
    {
          ptr->ptr_1 = malloc(10);
    }
    
    int main()
    {
          struct ex *ptr_whatever;
          char buffer[10];
    
          ptr_whatever = &whatever;
          getmem(ptr_whatever);
          fgets(buffer, sizeof buffer, stdin);
          strcpy(ptr_whatever->ptr_1, buffer);
          puts(ptr_whatever->ptr_1);
          return 0;
    }
    ...the only difference i can see is that the pointer is stored within a structure but its memory is allocated so that it can still be used by main. in the first case strcpy causes a seg fault and in the second case everything works perfectly. why is this so?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    2,701
    in the above case the memory is apparently allocated inside getmem, then disappears once getmem returns, but in the below case...
    Since blah is a global variable, the memory does not go out of scope when the function returns. The first program works for me.


    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I'm donating my vector lib.
    By User Name: in forum C Programming
    Replies: 23
    Last Post: 06-24-2010, 06:10 PM
  2. Where does compiler allocate memory for Char x[] = "abc" ?
    By meili100 in forum C++ Programming
    Replies: 13
    Last Post: 10-20-2009, 05:02 AM
  3. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  4. Allocate a big dynamic memory location
    By vnrabbit in forum C Programming
    Replies: 11
    Last Post: 10-09-2002, 08:02 AM
  5. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 09:37 AM

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