c - glibc detected - double free or corruption (!prev) -



c - glibc detected - double free or corruption (!prev) -

i'm getting error may see in title, , can't figure out why.

the code:

class="lang-c prettyprint-override">#include <cstdlib> #include <cstdio> struct cdata { int* num; char* adr; char* ph; void (*init)(cdata* owner); void (*del)(cdata* owner); char* (*getadr)(cdata* owner); void (*setadr)(cdata* owner, char* adr); }; void cdata_init(cdata* owner) { owner->num = (int*)malloc(sizeof(int)); owner->adr = (char*)malloc(sizeof(char)*255); owner->ph = (char*)malloc(sizeof(char)*255); } void cdata_del(cdata* owner) { free(owner->num); free(owner->adr); free(owner->ph); } char* cdata_getadr(cdata* owner) { homecoming owner->adr; } void cdata_setadr(cdata* owner, char* adr) { owner->adr = adr; } int main() { cdata* info = (cdata*)malloc(sizeof(cdata)); data->init = cdata_init; data->del = cdata_del; data->getadr = cdata_getadr; data->setadr = cdata_setadr; data->init(data); data->setadr(data, "asdasd"); printf("%d", data->getadr(data)); data->del(data); free(data); homecoming 0; }

so think error caused char* manipulations don't know why.

what want want possible pass string parameter data->setadr , want assigned variable afterwards.

compiling line:

gcc -o test main.cpp

data->setadr(data, "asdasd"); problematic.

you setting address of memory block not allocated malloc , later trying free free. freeing such memory blocks (not allocated malloc) except null pointer lead undefined behavior.

this leaking atleast 255 bytes of memory in case. valgrind can help understand improve in case.

changing next function should prepare (rename appropriately)

void cdata_setadr(cdata* owner, char* adr) { strcpy(owner->adr, adr); /* include cstring */ }

c

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -