0

Code:

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

typedef struct{
    int *arr;
}example;

void Create(example var){
    var.arr = (int *)malloc(sizeof(int)*2);
}

int main(){
    example var1, var2;
    var1.arr = (int *)malloc(sizeof(int)*2);
    var1.arr[0] = 11;
    var1.arr[1] = 22;
    printf("%d %d\n",var1.arr[0],var1.arr[1]);
    Create(var2);
    var2.arr[0] = 111;
    var2.arr[1] = 222;
    printf("%d %d\n",var2.arr[0],var2.arr[1]);
    return 0;
}
OUT:
11 22
Segmentation Fault

My code is as above. I don't get any error when I do it manually as in var1. But if I do it inside a function as in var2, I get an error. How can I fix this. I want to do it inside the function.

EDIT:Thank you for your answers. It worked

1
  • 5
    Create has its argument passed by value. Calling Create(var2) does not modify var2 in any way, what's passed is a copy. You probably want Create to take a pointer as an argument, or return a new example. Commented Jul 13, 2021 at 17:49

3 Answers 3

1

you have to pass reference of var2: Create(&var2);

Sign up to request clarification or add additional context in comments.

Comments

0

The function parameter

void Create(example var){
    var.arr = (int *)malloc(sizeof(int)*2);
}

is its local variable that is initialized by the passed argument and is not alive after exiting the function.

That is this call

Create(var2);

did not change the variable var2 declared in main.

As a result in these statements

var2.arr[0] = 111;
var2.arr[1] = 222;

there is used uninitialized pointer arr that has an indeterminate value that invokes undefined behavior.

You need to pass the variable by reference to the function. For example

void Create(example *var){
    var->arr = (int *)malloc(sizeof(int)*2);
}

and the function is called like

Create( &var2 );

Comments

0

The problem is that Create() is making a COPY of your struct. The original struct is unchanged.

If your program was C++, you'd want to pass a "reference".

Here, you want to pass a pointer:

void Create(example * mystruct){
    mystruct->arr = (int *)malloc(sizeof(int)*2);
}

int main(){
    example var1, var2;
    ...
    Create(&var2);

Comments

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.