Home > Mobile >  segFaut by allocating memory for pointer to pointer in struct
segFaut by allocating memory for pointer to pointer in struct

Time:12-05

I have a pointer to char pointer in a struct. so there is a struct poiter object that I will pass to thread but thats not relevant.

so this is my struct

struct shard
{
    sem_t *semaphore_o;
    char **input;
    char **image_o;
};

I am creating object like

struct shard *obj=malloc(sizeof(struct shard));

and I am allocating the input in shard struct

*(obj->input)=malloc(sizeof(char) 1);

but abocve line giving segFault

CodePudding user response:

*(obj->input) dereferences input before input points to valid memory, invoking undefined behavior, where manifesting with a segfault is common. You first have to malloc memory for it before dereferencing. You don't provide enough details about what you're trying to do, but something like:

struct shard *obj=malloc(sizeof(struct shard));
if (obj == NULL)
{
  // handle error how you want, and make a check like this for every malloc
  exit(-1);
}

obj->input = malloc(howManyCharPtrsYouWant * sizeof(*(object->input));
for (int i=0; i<howManyCharPtrsYouWant; i  )
{
  obj->input[i] = malloc(howManyCharsYouWant); // sizeof(char) is guaranteed to be 1, so no need to include it in `malloc`
}

See my previous answer for an explanation of sizeof(*(object->input)) if you're unsure what's happening there.

*(obj->input)=malloc(sizeof(char) 1); only allocates space for 2 chars (sizeof char == 1, 1 == 2 total). This is the smallest possible string you can have in C, one char followed by a NUL terminator. So if you're trying to put more than 2 chars in that buffer, that's an overflow --> UB --> possible segfault. If all you need is one char, better to bypass the malloc and simply use char c;, for example.

This is getting off topic, but the top two reasons you need dynamic memory allocation IMO are:

  1. You won't know how much memory you'll need until runtime
  2. You need "a lot" of memory (on your regular vanilla PC, I'd put this around 4 MB, but of course your mileage may vary depending on your needs and system).

SO has some good questions weighing the benefits of when to malloc or not, you can look them up.

If you know at compile time you'll need a max of 30 strings, only 30 chars long for example, then you can do something like

struct shard
{
    sem_t *semaphore_o;
    char input[30][30];
    // .. etc
};

and

struct shard obj; // you only need one of these, malloc makes little sense IMO
obj.semaphore_o = malloc(..); // this doesn't need to be a pointer either
strcpy(input[0], "hello there"); // fits in 29 chars plus NUL
strcpy(input[5], "I'm Jim");     // same

My preference is always to use automatic (stack) storage when possible, it's simpler because it relieves you of the burden of memory management.

  •  Tags:  
  • c
  • Related