c - Segfault -- but the pointer isn't NULL -


i doing following in c:

void *initialize() {     my_type *ret = malloc(sizeof(my_type));     return (void*)ret; }  void test() {     my_type* ret = (mytype*)initialize();     my_type x = *ret; } 

it crashes on dereference with:

received signal 11 (segmentation fault: 11) 

the pointer not null: tried printing pointer, , got value.

i tried making new my_type right in test function, this:

my_type* new = malloc(sizeof(my_type)); 

when print integer representations of new , ret, integers close each other. these things should nearby in memory.

if compiler not know function assumes int return type.

if size of int different function returns code generated compiler might miss return correct number of bytes.

however, code posted correct , perform expected, initialise() occurs before used, compiler knows type function returns.

most propably original code (you did not post) looks (without prototype initialise()):

try following:

#include <stdlib.h> /* pull in malloc's protoype. */  void * initialize(void);  void test() {     my_type x, * ret = initialize();     if (ret)       x = *ret; }  void * initialize(void) {     my_type * ret = malloc(sizeof(*ret));     return ret; } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -