9

I'm trying to malloc an array inside a struct but I keep getting segmentation errors when I run the program.

The compares function is just something I'm testing so it shouldn't be a part of the problem

typedef struct {
    char *string;
} prod_t;

int
main(int agrc, char **argv){
    int i = 0;
    prod_t *c = NULL;

    char str2[100] = "abcd";
    c->string = (char *) malloc( 5 * sizeof(char));
    strcpy(c->string,str2);

    compares(c->stock,str2,i);

    return 0;
}
3
  • 3
    You forgot to allocate memory for your prod_t *c. Commented May 18, 2015 at 17:16
  • Add c = malloc(sizeof *c);, then c->string = malloc(5 * sizeof *(c->string)); Commented May 18, 2015 at 17:21
  • Typically, in a case like this, you'd run the program under debugger, then see it crash on some line, then examine the values of variables on that line. In this case you'd see that c is NULL when the program crashes as you try to access c->string. Commented May 18, 2015 at 17:27

3 Answers 3

5

The problem is that you're allocating space for the string, but you're not allocating the struct at all. c remains set to NULL and you're trying to dereference it.

Allocate space for the struct before assigning to its members

prod_t *c = malloc(sizeof(prod_t));

And, as a sidenote for your next-to-fix error: this field doesn't exist

c->stock
Sign up to request clarification or add additional context in comments.

Comments

4

You need to allocate space for the struct before you can assign to the string member:

prod_t *c = malloc(sizeof(prod_t));

Also see Do I cast the result of malloc?

Comments

2

First of all, don't cast result of malloc. You only need to do that in C++. In C, it can actually hide potential problems.

Second of all, you need to allocate (or statically declare) your structure.

Third, c->stock doesn't exist. You probably meant c->string.

typedef struct {
    char *string;
} prod_t;

int
main(int agrc, char **argv) {
    int i = 0;
    prod_t *c = malloc( sizeof( prod_t ));


    char str2[100] = "abcd";
    c->string = malloc( 5 * sizeof(char));
    strcpy(c->string,str2);

    compares(c->string,str2,i);

    return 0;
}

2 Comments

String literals automatically get a 0 terminator, you don't need to do it explicitly.
What, you expect me to pay attention or something :) I fixed it now.

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.