Reputation: 19
I'm able to assign values with strdup
and print the values with this: (*test + index)->email
but I have no idea how to free the memory allocated to the variable email. I thought about freeing test+index
but I guess this would cause a memory leak, right? Taking into account that the struct has allocated memory and each of the pointer inside it have memory allocated with strdup
.
Edit:
The code is roughly like this:
struct random {
char *email;
} Random;
void function(Random **struct) {
char *temp = calloc(100, sizeof(char));
*struct = calloc(5, sizeof(Random));
for (int i = 0; i < 5; i++) {
scanf("%s", temp);
(*struct + i)->email = strdup(temp); //This works
}
free((*struct + 3)->email); //Gives segmentation fault
}
int main() {
Random *struct;
function(&struct)
}
Upvotes: 1
Views: 252
Reputation: 96
If I'm not mistaken, wouldn't it this?
free(*(test+index)->email);
free(text+index);
Upvotes: 1
Reputation: 144695
The posted code does not compile:
struct
as the name of a variable. struct
is a keyword.Random
is a global variable, not a type.It is idiomatic and much simpler in C to return the result instead of passing its address as an argument.
Following these remarks, and adding basic checks, the code should be simplified as:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Random {
char *email;
} Random;
Random *function(void) {
char *temp = calloc(100, sizeof(char));
if (temp == NULL)
return NULL;
Random *s = calloc(5, sizeof(Random));
if (s != NULL) {
for (int i = 0; i < 5; i++) {
if (scanf("%99s", temp) != 1)
*temp = '\0';
(s + i)->email = strdup(temp); //This works
}
free((s + 3)->email); //Gives segmentation fault
}
free(temp);
return s;
}
int main() {
Random *s = function();
// ...
}
This code, semantically equivalent to your posted fragment, does not have undefined behavior where you indicate, your actual code must be doing something else.
Upvotes: 1
Reputation: 16540
please read/understand: precedence of C operators
Then note that the de-reference operator *
has a lower precedence than the +
operator,
Therefore, The posted code needs to be modified to use something like:
(*mystruct)+i = ...
etc. Otherwise, the +
will be executed before the *
Upvotes: 0