Thread: mallocating a struct

  1. #1
    Engineer in research :(
    Join Date
    May 2007
    Location
    Calgary
    Posts
    56

    mallocating a struct

    struct database_input {
    char *catA;
    int catB;
    double catC;
    int catD;
    };

    lets say i want to establish an array of structs called data, and I want to dynamically allocated .

    So far I have written this:
    Code:
    data = malloc((i+1) * sizeof(*data)); //where i+1 is the size I want
    
    while(j<i) //where j starts off 0 and i is the last index
    {
     printf("size: %d\n", sizeof(data));
    data[j].catA = (char*)malloc(strlen(a[j])*sizeof(char));  
    //a is an array of strings (char**) so a[j] is the string inposition j.
    
    j++;
    }
    I didn't continue on because when I tried to compile it, a segmentation error occurs at the lines data[j].branchnumber...

    Did I do something wrong, how can I fix this?

    Thanks
    Firyace
    Undergraduate Research
    Electrical and Biomedical Engineering Department
    University of Calgary

    My Comp:
    |Core 2 Duo 6420 4mb cache| Corsair 2*1Gb memory pc5400|
    |500Gb and 80Gb Sata2| HIS 1950pro Turbo OC 256mb ViVo|
    |X-Cube2 red micro atx case| 3in1 Tiger Game port|
    |ASUS P5B-LD2 Rev2.0-VM| WindowsXP Pro SP2| Fedora 8|
    |Windows XP Pro 64|

    My Store
    Real estate 43

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    > data = malloc((i+1) * sizeof(*data));
    Given your while loop which follows, you only need 'i' elements, not i+1

    > data[j].catA = (char*)malloc(strlen(a[j])*sizeof(char));
    If you're following this with strcpy to data[j].catA, then you're 1 char short.
    strlen() doesn't count the \0, but strcpy will copy it.

    Say
    data[j].catA = malloc( (strlen(a[j])+1)*sizeof(*data[j].catA) );
    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.

  3. #3
    Engineer in research :(
    Join Date
    May 2007
    Location
    Calgary
    Posts
    56
    hi,
    I tried that and the error is still the same, hangs at the same line.
    Firyace
    Undergraduate Research
    Electrical and Biomedical Engineering Department
    University of Calgary

    My Comp:
    |Core 2 Duo 6420 4mb cache| Corsair 2*1Gb memory pc5400|
    |500Gb and 80Gb Sata2| HIS 1950pro Turbo OC 256mb ViVo|
    |X-Cube2 red micro atx case| 3in1 Tiger Game port|
    |ASUS P5B-LD2 Rev2.0-VM| WindowsXP Pro SP2| Fedora 8|
    |Windows XP Pro 64|

    My Store
    Real estate 43

  4. #4
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Here is an example on how to malloc structs and there member data.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct infoStruct{
    	char *data;
    	int value;
    };
    
    int main()
    {
    	const int bufSize = 10;
    	int i = 0;
    	struct infoStruct *pInfoStruct = NULL;
    
    	/*Allocate our struct out*/
    	pInfoStruct = malloc(sizeof(struct infoStruct) * bufSize);
    
    	/*Make sure our struct was allocated*/
    	if(NULL == pInfoStruct){
    		return 0;
    	}/*if*/
    
    	/*Allocate our member data*/
    	for(i = 0; i < bufSize; i++){
    		/*Allocate the string*/
    		pInfoStruct[i].data = malloc(sizeof(char) * bufSize);
    		
    		if(NULL == pInfoStruct[i].data){
    			break;
    		}/*if*/
    
    		/*Copy Hello into the data buffer*/
    		strcpy(pInfoStruct[i].data, "Hello");
    
    		/*Set the value to i*/
    		pInfoStruct[i].value = i;
    	}/*for*/
    
    	/*Print out the value*/
    	for(i = 0; i < bufSize; i++){
    		/*Make sure we have valid data*/
    		if(NULL == pInfoStruct[i].data){
    			break;
    		}/*if*/
    
    		printf("&#37;s: %d\n", pInfoStruct[i].data, pInfoStruct[i].value);
    	}/*for*/
    
    	/*So we can see it*/
    	getchar();
    
    	/*Free Up The Values*/
    	for(i = 0; i < bufSize; i++){
    		free(pInfoStruct[i].data);
    	}/*for*/
    
    	free(pInfoStruct);
    
    	return 0;
    }
    I think the comments and such in the code should handle the explaination.
    Woop?

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    > I tried that and the error is still the same, hangs at the same line.
    Unfortunately, when dealing with malloc related problems, you have to examine all your use of malloc, not just the one which is failing.

    If you repeated the same "off-by-one" mistake somewhere else in the code, then those need to be fixed as well.

    If you can, post a complete program which crashes. Short snippets are not going to help since we can easily make the snippets work perfectly in isolation, but they will still fail in your main program.
    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.

  6. #6
    Registered User
    Join Date
    May 2007
    Location
    Södertälje, Sweden
    Posts
    2
    I believe that the problem could be caused by the following line:

    Code:
    data = malloc((i+1) * sizeof(*data)); //where i+1 is the size I want
    Is it not quite illegal to dereference an uninitialized pointer or null pointer (the original post does not say). I'm refering to the usage of *data together with the sizeof operator.

    Do it like this instead:

    Code:
    data = malloc( i * sizeof( struct database_input ) )

  7. #7
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    Quote Originally Posted by philip79 View Post
    Is it not quite illegal to dereference an uninitialized pointer or null pointer (the original post does not say). I'm refering to the usage of *data together with the sizeof operator.
    You're right that you cannot dereference an uninitialized or null pointer. However, in sizeof(*data), you're not derefencing. It's taking the size of the structure itself, not the pointer. Consider this example:
    Code:
    #include <stdio.h>
    
    struct databucket
    {
    	int data1, data2, data3, data4, data5;
    };
    
    int main()
    {
    	struct databucket *somedata;
    
    	somedata = NULL;
    
    	printf("sizeof(somedata) = &#37;u\n", sizeof(somedata));
    	printf("sizeof(*somedata) = %u\n", sizeof(*somedata));
    
    	return 0;
    }
    That will output:
    Code:
    sizeof(somedata) = 4
    sizeof(*somedata) = 20
    Where 20 is the size, in bytes, of a "databucket" structure, and 4 is the size, in bytes, of a pointer, on my system.

    Do it like this instead:

    Code:
    data = malloc( i * sizeof( struct database_input ) )
    The argument against doing that is that if you ever change data's type, you must also change the associated malloc() statements (and anywhere else you use sizeof()).
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  8. #8
    Registered User
    Join Date
    May 2007
    Location
    Södertälje, Sweden
    Posts
    2
    Ok.

    You learn new things every day. :-)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segfault with Linked List Program
    By kbrandt in forum C Programming
    Replies: 1
    Last Post: 06-23-2009, 07:13 AM
  2. Replies: 1
    Last Post: 12-03-2008, 03:10 AM
  3. Replies: 10
    Last Post: 05-18-2006, 11:23 PM
  4. What's wrong with my search program?
    By sherwi in forum C Programming
    Replies: 5
    Last Post: 04-28-2006, 09:57 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM