0

I am attempting to return a server structure pointer in this function in C. There's no issues when I compile this code, but when during execution, the line test->port is causing an AddressSanitizer issue.

---header file---

struct gfserver_t{ //fxw
        int port;
        int max_npending;
    };

---c file---

gfserver_t* gfserver_create(){
    struct gfserver_t* test;
    memset(&test, 0, sizeof(test));
    test->port=22;//==30022==ERROR: AddressSanitizer: SEGV on unknown address
    return test;
}

I tried gdb, looking up the causes of AddressSanitizer (dereferencing a null pointer), and how to set pointer structure members and still don't understand how I am running into this issue. Any pointers would be great.

Yaga
  • 115
  • 3
  • 17
  • You never allocate an object of type `struct gfserver_t`. Either `malloc` or change the type of `test` from `struct gfserver_t*` to `struct gfserver_t`. It doesn't seem like you actually need a dynamic object. Your struct is happy to be copied as it currently stands. – bitmask Jul 22 '20 at 00:32
  • Thanks for the tip. I added the line: test=(struct gfserver_t *) malloc(sizeof(struct gfserver_t)); but it still doesn't work. Any pointers on this? Sorry I'm pretty new to C – Yaga Jul 22 '20 at 21:45
  • Given that you are new to C, I suspect you have recently begun learning it, possibly teaching it to yourself. There is zero reason to learn and use C today unless you want to contribute to existing C projects. C is a broken language (yes, this is my private opinion). Learn C++. It can replace C in any situation and it has a functioning type system. Check out [The Definitive C++ Book Guide and List](https://stackoverflow.com/q/388242/430766). – bitmask Jul 22 '20 at 23:26
  • I got it working. The second issue was my use of memset(), where the first argument is supposed to be a pointer, so just using 'test' works. And as for C, it's for a future class I'll be taking unfortunately haha. – Yaga Jul 23 '20 at 17:09

0 Answers0