0

I'd like to pass an array of pointers of structure addresses which has varying size and access structure members. But by passing the array of structure objects the data is irregular and library functions are giving SIGABRT signal. This is a part of my code-

struct data *device_info;

device_info = malloc(device_count*sizeof(void );
ipbt_database_manager_get_device_info(device_info, "all", device_count);

This is the function definition-

bool ipbt_database_manager_get_device_info(struct data *dev_info_ptr, char *device_id, int device_count)
{
    struct node *current_device_info = first_device_info;
    int count = 0;

    if (!strcmp(device_id,"all")) {
        while (current_device_info != NULL) {
            dev_info_ptr[count] = current_device_info->node_data;
            count++;
            current_device_info = current_device_info->next;
        }
}
9
  • 2
    I'm curious. What do you think sizeof(void) is supposed to give you? Commented Feb 16, 2017 at 13:27
  • It gives enough space to store address of structure right? size of void is 4 bytes. Commented Feb 16, 2017 at 13:29
  • Where is node struct declared ? Commented Feb 16, 2017 at 13:29
  • @Govindh Replace that with sizeof(struct data) Commented Feb 16, 2017 at 13:30
  • node struct id declared and malloc' ed in a different c file. It is an existing database ie a linked list. Commented Feb 16, 2017 at 13:31

1 Answer 1

4

Your function expects a pointer to a structure, (possibly one of many the lie in consecutive memory).

This should allocate enough memory, which is the memory for a single struct data times device_count:

struct data *device_info = malloc(sizeof(*device_info) * device_count);
ipbt_database_manager_get_device_info(device_info, "all", device_count);

I omitted that check for NULL (which you must preform), and I united the pointer definition with its initialization.

Sign up to request clarification or add additional context in comments.

7 Comments

Does it copy the data to newly allocated memory or just copy the address of the original database(structure)?
@Govindh - It passes a consecutive buffer to ipbt_database_manager_get_device_info.
I just need to save the starting addresses of the structure database,not the whole thing. Is there any way to do that.
@StoryTeller Curious, any particular reason for malloc(count * sizeof *ptr) vs. malloc(sizeof *ptr * count)? I find the 2nd form better when malloc(sizeof *ptr * row * col) insures at least size_t math throughout the product calculation.
@chux - personal style preference. I just find the second form odd to read when the asterisk serves different purposes. Operator precedence while correct doesn't feel "natural" to me.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.