Thread: why does this structure require a malloc() line?

  1. #1
    Registered User
    Join Date
    Feb 2015
    Posts
    22

    why does this structure require a malloc() line?

    The code below runs. It is whittled down from a much larger program that was behaving strangely. When the malloc line is removed the strcpy line causes a segmentation fault at run time. I think it is because of the structure nvdat. I don't understand why the structure would require the malloc line.

    TIA. Bill S.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <malloc.h>
      
    char buf1[90] = "7";
    char buf2[90] = "8";
    
    struct nvdat {
    char *bf[90];
    } k[10];
    
    int main()
    {
    
    memmove(buf2, buf1, 3);  
    if ((k[0].bf[0] = malloc(20)) == NULL)
    printf("malloc error"); 
    
    strcpy(k[0].bf[0], buf2);
    printf("%5s \n",k[0].bf[0]);
    }

  2. #2
    Citizen of Awesometown the_jackass's Avatar
    Join Date
    Oct 2014
    Location
    Awesometown
    Posts
    269
    buf[n] is a pointer to a string, before malloc it doesent point to any meaningful memory location (not even stack memory) so that's why it segfaults.
    "Highbrow philosophical truth: Everybody is an ape in monkeytown" --Oscar Wilde

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,663
    1. malloc is prototyped in stdlib.h, not malloc.h

    2. Every * in your variable declarations needs to be made to point to some valid memory before you can use it.

    Eg.
    Code:
    int anArray[10];
    int anInt;
    int *myPointer;
    
    // Do any of these
    myPointer = anArray;
    myPointer = &anArray[0];  // same thing
    myPointer = &anInt;
    myPointer = malloc( 10 * sizeof(*myPointer));
    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. Structure and Malloc Confusion.
    By Kurtanius21 in forum C Programming
    Replies: 8
    Last Post: 12-13-2012, 08:00 PM
  2. Address of Structure element, and struct malloc
    By HellsChicken in forum C Programming
    Replies: 1
    Last Post: 11-14-2005, 02:41 PM
  3. using malloc for structure
    By Pea in forum C Programming
    Replies: 2
    Last Post: 11-22-2004, 04:01 AM
  4. Help require for some data structure topics
    By jawwadalam in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 12-15-2002, 07:09 PM
  5. Require information!!!!
    By sameer in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2002, 06:51 AM