#Segfault when working with C

1 messages · Page 1 of 1 (latest)

cyan oasis
#

I'm trying to work with the c postgres library. I can create a connection correctly, however I'm not able to create a struct around it:

const Pg = struct {
    conn: *pq.PGconn,

    pub fn init(addr: []const u8) !*Pg {
        var conn = pq.PQconnectdb(addr.ptr);

        if (pq.PQstatus(conn) != pq.CONNECTION_OK) {
            pq.PQfinish(conn);

            std.log.err("{s}", .{pq.PQerrorMessage(conn)});

            return error.ConnectionError;
        }

        var pg = Pg{ .conn = conn.? };
        return &pg;
    }

    pub fn exec(self: *Pg, query: []const u8) !*pq.PGresult {
        var res = pq.PQexec(self.conn, query.ptr);

        switch (pq.PQresultStatus(res)) {
            pq.PGRES_EMPTY_QUERY => return error.ExecEmpty,
            else => return error.ExecUnknown,
        }

        return res;
    }

The init function works correctly, but the exec function throws a segfault.

If I move the code from exec inside init, everything seems to be working ok

The segfault happens at the var res = pq.PQexec(self.conn, query.ptr); line.

Any ideas??
Thanks!:)

languid stream
#

i'm guessing the problem is on this line in init():

return &pg;
#

why are you returning a pointer? if possible return it by value and this may fix the issue

cyan oasis
#

Let me check!

#

This worked! :D

#

But why?

languid stream
cyan oasis
#

Nope :(

languid stream
cyan oasis
#

Thanks again!

languid stream
#

for sure. let me know if you have any questions.

#

you must beware of returning pointers to locals. the memory gets invalidated when the function returns. but you might not notice until the stack gets used again by another function.

cyan oasis
#

I see

#

Shouldn't the compiler warn about this?

languid stream
#

there have been many github issues about this. let me see if i can find one

#

i agree that it would be nice for the compiler to error when this happens. it may be easy to detect in simple cases. but not so easy for more complex ones.

cyan oasis
#

Yeah

#

Thanks for all the info and knowledge!

#

Hopefully it gets for 0.12.0

languid stream
#

another thing to consider is that comptime semantics are different. the comptime interpreter acts more like a high level language so its ok to return a pointer to locals and use it.

lucid trellis