1

I've been working on this problem for quite some time now, can't seem to find an answer anywhere. The problem is fairly simple, I was given a sample program and asked to fix the error (This is a homework problem for University).

Here is the program in C:

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

typedef struct 
{
    int a;
    char *b;
} Cell;
void AllocateCell(Cell * q) 
{

    q =(Cell*) malloc (sizeof(Cell));
    q->b = (char*)malloc(sizeof(char));

}
int main (void) 
{

    Cell * c;
    AllocateCell(c);
    c->a = 1; // Produces Seg Fault

    free(c);
    return 0;
}

The Segmentation fault is produced by the line:

c->a = 1;

Clearly the seg fault comes from some part of the memory allocation, but I'm not quite sure from where.

Ben Nordin
  • 45
  • 1
  • 6
  • Study double pointer and how to pass it as an argument to a function i.e. pass-by-value and pass-by-reference. The pointer variable `q` is local to function. It is changed inside the function only causing a memory leak. The pointer variable `c` in `main` function is not changed. – Azeem Apr 11 '19 at 04:49
  • In C arguments to functions are passed *by value*. That means the value is *copied*, and all the function have is the local copy in the local argument variable. Modifying the copy (by e.g. assignment) will not modify the original. Do some research about *emulating pass by reference in C*. – Some programmer dude Apr 11 '19 at 04:50
  • Or a much *much* simpler solution in this case: ***Return*** the pointer from the function. No need to pass an argument at all. – Some programmer dude Apr 11 '19 at 04:51
  • On another note, `malloc(sizeof(char))` will allocate space for a ***single*** character. That's not even space for a one-character string, since strings need to be *null-terminated* and the null-terminator (not to be confused with the `NULL` pointer) also needs space in the string. Oh, and `sizeof(char)` is specified to *always* be equal to `1`. – Some programmer dude Apr 11 '19 at 04:53
  • Lastly, in C you [should not cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). – Some programmer dude Apr 11 '19 at 04:53
  • So I made AllocateCell's parameter Cell ** q, passed Cell * c through by reference, and called *q = malloc...... instead of q = malloc.... and it works! Thank you very much! – Ben Nordin Apr 11 '19 at 05:03

0 Answers0