Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate struct on the heap in C [duplicate]

#include <stdio.h>
#include <stdlib.h>

struct myStruct
{
    int number;
};

void
allocateMem(struct myStruct *struct1)
{
    struct1 = malloc(sizeof(struct myStruct));
    struct1->number = 500;
    printf("struct1->number: %d\n", struct1->number);
}

int
main(int argc, char *argv[])
{
    struct myStruct *struct1 = NULL;
    allocateMem(struct1);
    printf("number: %d\n", struct1->number);
    return 0;
}

Hello citizens of StackOverflow, I seek your assistance.

What I am trying to do is allocate a struct using heap space rather than stack space; and I am trying to do the allocation inside of a function. No matter how much I mess with this I always get either a segmentation fault or several compiler warnings.

I'm doing something here incorrectly, but I can't figure out what, I've been all over StackOverflow and the general internet trying to find an example or post that relates to my issue but I have not found anything.

If you could tell me what I'm doing wrong, or just point me in the right direction I would be extremely grateful.


Thank you everyone for your quick and accurate replies. You were correct, I needed a pointer to a pointer, my code works now thanks to your help.

like image 746
yellowhat5 Avatar asked May 03 '14 06:05

yellowhat5


People also ask

Are structs heap allocated?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Are structs stored in heap C?

Most importantly, a struct unlike a class, is a value type. So, while instances of a class are stored in the heap, instances of a struct are stored in the stack.


1 Answers

In this function,

void
allocateMem(struct myStruct *struct1)
{
    struct1 = malloc(sizeof(struct myStruct));
    struct1->number = 500;
    printf("struct1->number: %d\n", struct1->number);
}

struct1 is passed by value. Any changes you make to it in the function are not visible from the calling function.

A better alternative:

struct myStruct* allocateMem()
{
    struct myStruct *struct1 = malloc(sizeof(struct myStruct));
    struct1->number = 500;
    printf("struct1->number: %d\n", struct1->number);
    return struct1;
}

Change the calling function to:

int
main(int argc, char *argv[])
{
    struct myStruct *struct1 = allocateMem();
    printf("number: %d\n", struct1->number);

    // Make sure to free the memory.
    free(struct1);

    return 0;
}
like image 169
R Sahu Avatar answered Oct 01 '22 14:10

R Sahu