Let's say I have a struct like this:
typedef struct {
unsigned s_i, s_j;
unsigned d_i, d_j;
} obs_t
I want to define a function:
obs_t * string_to_struct (char * s);
Which reads a string formatted, for example, like this: "1 1 4 6" and passes the four number to the struct obs_t. So far I was not able of avoiding segmentation fault, i'm using the following code:
obstacle_t * string_to_obstacle (char * s){
obstacle_t *ostacolo = malloc(sizeof(obstacle_t));
unsigned int **format;
sscanf(s, "%u %u %u %u", format[0], format[1], format[2], format[3]);
ostacolo -> s_i = *format[0];
ostacolo -> s_j = *format[1];
ostacolo -> d_i = *format[2];
ostacolo -> d_j = *format[3];
}
You never initialize the pointer value format , so it has indeterminate value and dereferencing it has undefined behavior. With a pointer to pointer to int you'd have to allocate space for 4 pointers to int and point format at that, and then allocate space for 4 integers and set the pointers to point to those.
You also do not check the return values of malloc and sscanf, so you might be either dereferencing a NULL pointer, or assigning/leaving unspecified values to ostacolo's fields, if the sscanf fails. You also have no return statement in your non-void function.
Here's a version of string_to_obstacle that addresses these issues:
obstacle_t * string_to_obstacle (char * s)
{
obstacle_t *ostacolo = malloc(sizeof *ostacolo);
if (!ostacolo) {
return NULL;
}
if (sscanf(s, "%u %u %u %u", &ostacolo->s_i, &ostacolo->s_j, &ostacolo->d_i, &ostacolo->d_j) < 4) {
free(ostacolo);
return NULL;
}
return ostacolo;
}
It's good to keep in mind that sscanf has no way to handle passing larger integers than fit in an unsigned integer in the string. The behavior is undefined .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.