Home > Back-end >  why can't i access the pointer to a structure from another file and get the members
why can't i access the pointer to a structure from another file and get the members

Time:09-10

this a reproducible example and not the entire code the entire code is too large.. my problem was that i had a structure that i created using malloc and i needed to access it from another function in another file, but i keep getting segfault...

header file main.h

#ifndef main_a
#define main_a
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct cmd_s
{
     int n;
} cmd_t;

extern cmd_t *ptr;
void push(char *line);

#endif

the main.c file main.c

#include "main.h"
cmd_t *ptr = NULL;

int main(void)
{
    cmd_t *ptr = malloc(sizeof(cmd_t));
    ptr->n = 5;
    push("line");
    
    return (0);
}

and where i need to access the struct from named opcode.c

opcode.c

#include "main.h"

void push(char *line)
{
    int new = ptr->n;
}

note that this is not the actual code the actual code has useful values, this is an example that contains the challenge i am facing

i tried to use static instead but i got the same error. i'm still a novice in c programming.. and i don't want to change the way i created the structure, which is through malloc because another function depends on it... i just need to make that malloced structure accessible to another file in the program. thanks.

CodePudding user response:

int main(void)
{
    cmd_t *ptr = malloc(sizeof(cmd_t));

You create new ptr variable visible only in function main. Your push see the global pointer ptr but not the one you have malloced.

You need to

int main(void)
{
    ptr = malloc(sizeof(*ptr));
    /* .... */

Use obiects not types in sizeof (as in this example)

  • Related