简体   繁体   中英

How to allocate memory inside a struct and outside main?

I'm a beginner at C and I'm having trouble trying to allocate memory outside main function.

My goal is to create a pointer (that is inside my struct) int-sized. If it has NULL value, pass it to the struct element and it has to be recognizable to the main function.

I tried everything that I could imagine but I never felt so stuck before, sorry for not giving any more information.

struct info {
    int *data;
};

void allocate(struct info *ptr);

int main()
{
    struct info *p;
    struct info a;

    p = &a;
    allocate(p);
    free(p->data);
    return 0;
}

void allocate(struct info *ptr)
{
    if(ptr->data == NULL)
    {
        ptr->data = malloc(sizeof(int));
    }
}

I expect that data should be recognizable by main as having the size int and if you can help me how to free the same pointer afterwards, it would be very helpful. Thank you.

This is simply not possible directly. There's no way you can get the size of the allocated memory from the returned pointer by the allocator functions.

The best bet, would be, to have another member variable to store the size for the allocated memory, and updated with the value of size, once the allocation is successful.

That said,

if(ptr->data == NULL)

is not likely to be TRUE, as you might have expected, because, ptr->data is uninitialized and the content is indeterminate. You got to make ptr->data point to a valid memory location anyways, so that check does not hold any meaning anyways.

As pointed out, your struct is uninitialized so it is not likely filled with NULL . The simplest way to get a zero-initialized struct in C is to use {0} :

struct info a = {0};

You can eliminate your extra p variable by calling allocate(&a); directly.


As a simpler example:

int main(void) {
    int *p;
    if (p == NULL) { // probably false
      // ...
    }
}

the pointer above is uninitialized. Unlike other languages (such as Java) p is not guaranteed to be anything.


An alternative approach I'd recommend to what you're doing is to create helper functions to both create and destroy info objects.

#include <stdlib.h>

struct info {
  int *data;
};

struct info* new_info(void);
void free_info(struct info* p);


int main(void) {
  struct info *p = new_info(); // user doesn't worry about creation details
  // ... use p ... 
  free_info(p); // user doesn't worry about deletion details
}

struct info* new_info(void) {
  struct info* p = malloc(sizeof *p);
  p->data = malloc(sizeof *p->data);
  return p;
}

void free_info(struct info* p) {
  free(p->data);
  free(p);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM