I wanted to add values into my. array
typedef struct teleporter {
int start;
int end;
}teleporters;
int main(int argc, char **argv) {
int lenght = 2;
teleporters *teleportPlaces;
teleporters mytele;
mytele.start = 0;
mytele.end = 0;
teleportPlaces = calloc(2, sizeof(teleporters));//malloc (sizeof(teleporters) * (lenght));
if (teleportPlaces != NULL) {
teleportPlaces = NULL;
}
for (int i = 0; i < lenght; i ) {
teleportPlaces[i] = mytele;
}
printf("Teleport END[0] = %d",teleportPlaces[0].end);
free(teleportPlaces);
return 0;
}
but everytime i add it, it gave me an segmentation error,
how do i solve this error? it'll be great if there's an article or answer about it, thanks
CodePudding user response:
The problem is that you are literally throwing away the address to your teleportPlaces right after allocating it.
Remove the if statement in which you point teleportPlaces to NULL.
In the for loop, the address teleportPlaces[i] is supposed to be the address to the beginning of your array (teleportPlaces) and an offset (i). But when you reassign it to rather point to NULL, the actual address to the array is lost, leaving you with memory leakage (since you can't free a calloc if you don't know the address to it).
CodePudding user response:
This if statement
if (teleportPlaces != NULL) {
teleportPlaces = NULL;
}
does not make a sense. It means that if the memory was allocated successfully you set the pointer teleportPlaces
to the allocated memory to NULL
, producing a memory leak.
After that you are using this null pointer in the following for loop.
Remove this if statement or for example write
if (teleportPlaces == NULL) return 0;
Or
if (teleportPlaces != NULL) {
for (int i = 0; i < lenght; i ) {
teleportPlaces[i] = mytele;
}
printf("Teleport END[0] = %d\n",teleportPlaces[0].end);
}
free( teleportPlaces );
Also you could simplify this code snippet
teleporters mytele;
mytele.start = 0;
mytele.end = 0;
the following way
teleporters mytele = { .start = 0, .end = 0 };
Also do not use magic numbers like 2
. Instead of this statement
teleportPlaces = calloc(2, sizeof(teleporters));
you should write
teleportPlaces = calloc( length, sizeof(teleporters));