I've run across this problem: I implemented a function whish converts a string into a structure. I've got this structure:
typedef struct {
unsigned a, b;
unsigned c, d;
} struct_t;
The heading of the function is the following:
struct_t * string_to_struct (char * g)
\retval p pointer to new structure created; \retval NULL if the conversion is not successful. The convertion is not successful for strings such as "5 8 10 10" (I'm given a segmentation fault
error) but is successful for strings such as "5 6 6 7" or "4 5 6 8". I think the problem lies within the allocation of memory for pointer to structure p.
I thought about first allocating memory for p in this way:
p = (struct_t*)malloc(sizeof(struct_t));
And then I thought about reallocating memory for p due to make it room for the string (some strings are about 8 bytes and everything works fine, but if the string is about 10 bytes I get a segmentation fault
, because by allocating memory for p as above I make room for only 8 bytes), using function realloc()
to enlarge the memory where to put the structure and make it the size of the string, but I don't know how to do it properly.
Here it is how I attempted to implement the function, not using realloc()
:
struct_t * string_to_struct (char * g){
struct_t * p; /* pointer to new structure*/
int n;
n = sizeof(g);
if(sizeof(g) > sizeof(struct_t))
p = (struct_t*)malloc(n*sizeof(struct_t));
else
p = (struct_t*)malloc(sizeof(struct_t));
if(g[0] == '\0' ) /* trivial */
return NULL;
else
(*p).a = g[0];
(*p).b = g[2];
(*p).c = g[4];
(*p).d = g[6];
if((*p).a <= (*p).c && (*p).b <= (*p).d) /* check, the elements of the structure must satisfy those relations.*/
return p;
else
return NULL; /* convertion not successful */
}
But it's not working. Thanks in advance for any help.