C free() double free or corruption (global array) - c

Here is a struct in header-file:
typedef struct Missile {
int id;
Model *model;
Point3D coords;
int counter;
float speed;
float yaw;
float pitch;
float roll;
} Missile;
and here is code from C-file:
#define INIT_MISSILE_ARRAY_SIZE 4
/* An array to keep track of all missiles created (fired) */
static Missile *missiles[INIT_MISSILE_ARRAY_SIZE];
/* This keeps track of the array missiles' size */
int currentArraySize = INIT_MISSILE_ARRAY_SIZE;
int numOfMissiles = 0;
Missile *CreateMissile()
{
if (numOfMissiles < currentArraySize)
{
Missile *missile = malloc(sizeof(Missile));
missile->model = LoadModelPlus("rocket1.obj");
missile->counter = 0;
missile->speed = 0.00;
missile->yaw = 0.00;
missile->pitch = 0.00;
missile->roll = 0.00;
missile->id = numOfMissiles;
missiles[numOfMissiles] = missile;
numOfMissiles++;
printf("Missile created, numOfMissiles: %d\n", numOfMissiles);
return missile;
}
printf("Too many missiles fired already.\n");
return NULL;
}
void DeleteMissile(Missile *missile)
{
free(missile);
}
gives me this error: double free or corruption (fasttop): 0x000000000234f5d0
when the function DeleteMissile(Missile *missile) is called. I have tried replacing free(missile); with free(missiles[missile->id]);, which finds the (same) missile in the global array of missiles and calls free() on that one, and this gives me the same error. The function LoadModelPlus() uses malloc for the missile->model.
Can anyone see what I'm doing wrong?

Related

Program received signal SIGTRAP when I return 2 structs

Im trying to read these 2 files and store its content into 2 differents structs so my program dont need to be reading it over and over again, the problem is when I try to run both structs the program crashes, when I try to debug it, it shows the title's error, however if I try to run only the products file or the sells file it works fine and shows the result.
The code:
#include <stdlib.h>
#include <stdio.h>
typedef struct sellsFile{
int year, month, day, code;
float sell_amount, price;
}sells;
typedef struct productsFile{
int code;
float stock_amount, uni_price, profit;
char type;
}products;
productsFile *read_productsFile(int *q);
sellsFile *read_sellsFile(int *q);
int main(){
int productsSize, sellsSize;
products *v_products;
sells *v_sells;
v_products = read_productsFile(&productsSize);
for(int cont=0;cont<productsSize;cont++){
printf("%d;%c;%.2f;%.2f;%.2f;\n",v_products[cont].code, v_products[cont].type,v_products[cont].stock_amount,v_products[cont].uni_price,v_products[cont].profit);
}
printf("\n\n\n");
v_sells = read_sellsFile(&sellsSize);
for(int cont=0;cont<sellsSize;cont++){
printf("%d/%d/%d %d %.2f %.2f\n",v_sells[cont].year,v_sells[cont].month,v_sells[cont].day,v_sells[cont].code,v_sells[cont].sell_amount,v_sells[cont].price);
}
}
productsFile *read_productsFile(int *q){
(*q) = 0;
FILE *archive;
products *result;
int code;
float stock_amount, uni_price, profit;
char type;
archive = fopen("products.txt", "r");
while(fscanf(archive,"%d;%c;%f;%f;%f;",&code,&type,&stock_amount,&uni_price,&profit) != EOF){
(*q)++;
result = (products *)realloc(result, sizeof(products) * (*q));
result[(*q)-1].code = code;
result[(*q)-1].type = type;
result[(*q)-1].stock_amount = stock_amount;
result[(*q)-1].uni_price = uni_price;
result[(*q)-1].profit = profit;
}
return(result);
}
sellsFile *read_sellsFile(int *q){
int year, month, day, code;
float sell_amount, price;
sells *result;
*q = 0;
FILE *archive;
archive = fopen("sells.txt","r");
while(fscanf(archive,"%d;%d;%d;%d;%f;%f;",&year,&month,&day,&code,&sell_amount,&price) != EOF){
(*q)++;
result = (sells *)realloc(result,sizeof(sells) * (*q));
result[(*q)-1].year = year;
result[(*q)-1].month = month;
result[(*q)-1].day = day;
result[(*q)-1].code = code;
result[(*q)-1].price = price;
result[(*q)-1].sell_amount = sell_amount;
}
return(result);
}
Example of produts file:
12100;P;17.400;2.30;38.80;
12200;P;25.000;23.70;13.58;
12300;P;16.090;17.48;12.75;
Example of sells file:
2015;1;1;15800;114.000;5.07;
2015;1;1;15600;9.000;9.79;
2015;1;1;12800;32.483;9.71;
Give the uninitialized value of result from this line of code:
sells *result;
this code results in undefined behavior:
result = (sells *)realloc(result,sizeof(sells) * (*q));
as results starts with an unknown value.

CPLEX MIP current node LP relaxation

During a MIP optimization with CPLEX C APIs is it possible to retrieve the linear relaxation (dual variables, reduced costs, etc ...) of the current node (i.e. every n nodes)?
I've registered a callback function (CPXsetsolvecallbackfunc) in order to be notified each time a new node is available. In the callback I use CPXgetcallbackinfo to retrieve the node information and CPXgetcallbacknodelp to retrieve the linear relaxation but unfortunately the procedure CPXsolution returns that no solution exists and the MIP optimization exits.
Here is a sample code realized starting from an IBM example where environment and problem are assumed to be properly initialized.
struct noderange {
int startnode;
int endnode;
};
typedef struct noderange NODERANGE;
NODERANGE nodeswritten;
nodeswritten.startnode = -1;
nodeswritten.endnode = 2100000000;
status = CPXsetsolvecallbackfunc(environment, usersolve, &nodeswritten);
if(status) {goto TERMINATE;}
status = CPXmipopt(environment, problem);
if(status) {goto TERMINATE;}
where the usersolve procedure is
static int CPXPUBLIC usersolve(CPXCENVptr env, void *cbdata, int wherefrom, void *cbhandle, int *useraction_p) {
int status = 0;
int nodecount;
static int count = 0;
CPXLPptr nodelp;
NODERANGE *nodeswritten;
*useraction_p = CPX_CALLBACK_DEFAULT;
nodeswritten = (NODERANGE *)cbhandle;
/* Find out what node is being processed */
status = CPXgetcallbackinfo(env, cbdata, wherefrom, CPX_CALLBACK_INFO_NODE_COUNT, &nodecount);
if (status) goto TERMINATE;
if (nodecount >= nodeswritten->startnode && nodecount <= nodeswritten->endnode) {
/* Get pointer to LP subproblem, then write a SAV file. */
status = CPXgetcallbacknodelp(env, cbdata, wherefrom, &nodelp);
if (status) goto TERMINATE;
int rows = CPXgetnumcols(env, nodelp);
int cols = CPXgetnumrows(env, nodelp);
int lpstat;
double objval;
double* x = (double*)malloc(sizeof(double) * CPXgetnumcols(env, nodelp));
double* dj = (double*)malloc(sizeof(double) * CPXgetnumcols(env, nodelp));
double* pi = (double*)malloc(sizeof(double) * CPXgetnumrows(env, nodelp));
double* slack = (double*)malloc(sizeof(double) * CPXgetnumrows(env, nodelp));
status = CPXsolution(env, nodelp, &lpstat, &objval, x, pi, slack, dj);
printf("Solutionstatus = %d\n", lpstat);
if (status) { goto TERMINATE; } // <--- HERE it returns no solution exists
free(x);
free(dj);
free(pi);
free(slack);
printf("[%d]\trows = %d cols = %d\t sol stat = %d\t z = %f\n", nodecount, rows, cols, lpstat, objval);
if (nodecount == nodeswritten->endnode) status = 1;
count++;
}
TERMINATE:
return (status);
}
I found out the problem, the callback is called before the subproblem has been solved so CPXsolution returns that no solution exists.

Dynamic Memory Allocation in C not working

I'm trying to make a game that requires dynamically sized arrays in C but my code isn't working even though identical code works in another one of my programs.
Here are my #includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SwinGame.h" //API for graphics, physics etc
#include <math.h>
Here are my typedefs for the relevant structs used:
typedef struct position_data
{
double x;
double y;
} position_data;
typedef enum enemy_type_data {CIRCLE, TRIANGLE, SQUARE} enemy_type_data;
typedef struct enemy_data
{
position_data location;
enemy_type_data type;
bitmap bmp;
double health;
double speed;
int path_to;
} enemy_data;
typedef struct enemy_data_array
{
int size;
enemy_data *data;
} enemy_data_array;
Here is the function to add an element to the array:
void add_enemy(enemy_data_array *enemies)
{
enemy_data *new_array;
enemies->size++;
new_array = (enemy_data *)realloc(enemies->data, sizeof(enemy_data) * enemies->size);
if (new_array) //if realloc fails (ie out of memory) it will return null
{
enemies->data = new_array;
// enemies->data[enemies->size - 1] = read_enemy_data();
printf("Enemy added successfully!\n");
}
else
{
printf("FAILED. Out of Memory!\n");
enemies->size--;
}
}
And here is my function call and variable declaration in the main procedure:
int main()
{
path_data my_path[41];
enemy_data_array enemies;
enemies.size = 0;
add_enemy(&enemies);
}
Why isn't this working?
You invoked undefined behavior by passing indeterminate value enemies->data in uninitialized variable having automatic storage duration. Initialize it before using add_enemy().
int main()
{
path_data my_path[41];
enemy_data_array enemies;
enemies.size = 0;
enemies.data = 0; /* add this line */
add_enemy(&enemies);
}
0 is a null pointer constant and can safely be converted to pointer NULL. Unlike NULL, 0 will work without including any headers. Of course you can use enemies.data = NULL; with proper header included.
#2501's explanation is completely correct. Another solution is to change your implementation of add_enemy() to something like this:
void add_enemy(enemy_data_array *enemies)
{
enemy_data *new_array;
// check if size was non-zero
if (enemies->size++)
{
new_array = (enemy_data *)realloc(enemies->data, sizeof(enemy_data) * enemies->size);
}
// start new allocation
else
{
new_array = (enemy_data *)alloc(sizeof(enemy_data) * enemies->size);
}
if (new_array) //if (re)alloc fails (ie out of memory) it will return null
{
enemies->data = new_array;
// enemies->data[enemies->size - 1] = read_enemy_data();
printf("Enemy added successfully!\n");
}
else
{
printf("FAILED. Out of Memory!\n");
enemies->size--;
}
}
If fails because you haven't cleared the content of "enemies". Since it is a stack variable, it will contain whatever garbage data is on the stack.
set enemies.data to NULL in the main function and try it again.

structures and pointers error: dereferencing pointer to incomplete type

ok I have three structs:
struct rss_s {
Radio_types device_type; // Its device_type which is defined by the typedef above Radio_Types
char * device_info; // some thing about the radio NAV/COM/etc.
char * device_model; // the Manufactures part/model number.
char * device_serial; // the device's serial number..
int power_48v; // power to the unit..
int power_400hz;
int panel_lamps; // turn off or on the Panel Lamps only
void * radio_info;
struct radio_s_C614L8
{
loopsw_614L8 loop_sw_614L8; this is an emum
modesw_614L8 mode_sw_614L8; this is an emum
int sw_band;
int sw_bfo;
int meter;
tuner *Tuner;
int tuners;
};
typedef struct tuner_s
{
char *device_name; // OS NAME
int frequency[tuned];
int power;
int dial_lamp;
void * back_radio; // back-link to radios[n]
void * back_info; // back-link to radio_xxxx
int fd[];
} tuner;
I initialize them in main.c
// Radio 614L8
static tuner tuner_C614L8[] = {{ .device_name = "/dev/TBD", }};
static struct radio_s_C614L8 radio_C614L8 = { .Tuner = &tuner_C614L8, .tuners = DIM(tuner_C614L8) };
static struct rss_s radios[] = {
{ .device_type = C614L8,
.device_info = "ADF",
.device_model = "614L8",
.device_serial = "8384",
.radio_info = &radio_C614L8,},};
the above works with out errors....
but when I try to initialize the the above radio... in my init_C614L8.c
with the following code I get an error...
error: dereferencing pointer to incomplete type in lines 4 & 6
int init_C614L8( struct rss_s * radios ){
int rw, i;
struct radio_s_614L8 * rad_info = radios -> radio_info;
tuner * this_tuner = rad_info -> Tuner;
// Now we will loop over the sub_devices....
for ( i = 0; i < rad_info -> tuners; i++ ) {
I think I have to cast something but not shure
Thanks
In rss.h you declare
struct radio_s_C614L8
but in init_C614L8.c you use
struct radio_s_614L8
which is declared nowhere.
Update:
To fix this error
error: dereferencing pointer to incomplete type
In init_C614L8.c (and any other place, but rss.h) replace
struct radio_s_614L8
by
struct radio_s_C614L8
The lesson learned here is either go for some glasses or some sleep! ;-) And also: "The compiler never lies!"
This means that the definition of struct radio_s_614L8 is not visible to the code where the errors are seen. You have either forgotten to include the definition or there are #if... directives removing the definitions or includes you think are there.

Segfault with pointer to char inside struct, ANSI C code

I'm having a strange behavior with the following simple ANSI C code. I have a pointer to a char inside a struct, and somehow, i have bad pointers, nulls and segfaults. Am i doing something stupid?
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#define MAX_ENTITIES 10
typedef enum
{
COMPONENT_NONE = 0,
COMPONENT_DISPLACEMENT = 1 << 0,
COMPONENT_VELOCITY = 1 << 1,
COMPONENT_APPEARANCE = 1 << 2
} component_t;
typedef struct
{
float x;
float y;
} Displacement;
typedef struct
{
float x;
float y;
} Velocity;
typedef struct
{
char *name;
} Appearance;
typedef struct
{
int entities[MAX_ENTITIES];
Displacement displacement[MAX_ENTITIES];
Velocity velocity[MAX_ENTITIES];
Appearance appearance[MAX_ENTITIES];
} scene_t;
typedef struct
{
int active;
scene_t *current_scene;
} game_t;
unsigned int entity_create(scene_t *scene)
{
unsigned int entity;
for (entity = 0; entity < MAX_ENTITIES; ++entity) {
if (scene->entities[entity] == COMPONENT_NONE) {
printf("Entity created: %u\n", entity);
return entity;
}
}
printf("Error! No more entities left!\n");
return MAX_ENTITIES;
}
unsigned int scene_add_box(scene_t *scene, float x, float y, float vx, float vy)
{
unsigned int entity = entity_create(scene);
scene->entities[entity] = COMPONENT_DISPLACEMENT | COMPONENT_VELOCITY | COMPONENT_APPEARANCE;
scene->displacement[entity].x = x;
scene->displacement[entity].y = y;
scene->velocity[entity].x = vx;
scene->velocity[entity].y = vy;
scene->appearance[entity].name = "Box";
return entity;
}
unsigned int scene_add_tree(scene_t *scene, float x, float y)
{
unsigned int entity = entity_create(scene);
scene->entities[entity] = COMPONENT_DISPLACEMENT | COMPONENT_APPEARANCE;
scene->displacement[entity].x = x;
scene->displacement[entity].y = y;
scene->appearance[entity].name = "Tree";
return entity;
}
unsigned int scene_add_ghost(scene_t *scene, float x, float y, float vx, float vy)
{
unsigned int entity = entity_create(scene);
scene->entities[entity] = COMPONENT_DISPLACEMENT | COMPONENT_VELOCITY;
scene->displacement[entity].x = x;
scene->displacement[entity].y = y;
scene->velocity[entity].x = vx;
scene->velocity[entity].y = vy;
return entity;
}
void update_render(scene_t *scene)
{
const int mask = (COMPONENT_DISPLACEMENT | COMPONENT_APPEARANCE);
unsigned int entity;
Displacement *d;
Appearance *a;
for (entity = 0; entity < MAX_ENTITIES; ++entity) {
if ((scene->entities[entity] & mask) == mask) {
d = &(scene->displacement[entity]);
a = &(scene->appearance[entity]);
printf("%s at (%f, %f)\n", a->name, d->x, d->y);
}
}
}
void game_init(game_t *game)
{
scene_t scene;
memset(&scene, 0, sizeof(scene));
game->current_scene = &scene;
game->active = 0;
scene_add_tree(game->current_scene, 5.0f, -3.2f);
scene_add_box(game->current_scene, 0.0f, 0.0f, 0.0f, 0.0f);
scene_add_ghost(game->current_scene, 10.0f, 4.0f, 0.0f, 0.0f);
}
void game_update(game_t *game)
{
update_render(game->current_scene);
}
int main(int argc, char **argv)
{
game_t game;
memset(&game, 0, sizeof(game));
game_init(&game);
while (game.active == 0) {
game_update(&game);
}
return 0;
}
In game_init, you are declaring a local variable of type scene_t. Once game_init ends, this variable no longer exists - you cannot use it correctly outside that function, but that's what you try to do when you access the scene inside your game_t variable.
If you want to create a scene_t which can be used outside of the function, you need to allocate the memory for it manually by using
scene_t* scene = malloc(sizeof(scene_t));
...and then working with it as a pointer instead.
You are saving a local address, when function goes out of scope "scene" will be destroyed.
scene_t scene;
memset(&scene, 0, sizeof(scene));
game->current_scene = &scene;
You should instead allocate scene
scene_t* scene = malloc(sizeof(scene_t));
The problem is that you're not allocating a scene:
scene_t scene;
memset(&scene, 0, sizeof(scene));
game->current_scene = &scene;
the scene_t object here is on the stack and that memory will be reclaimed once you exit from the function. You should instead use
scene_t *pscene = malloc(sizeof(scene_t));
memset(pscene, 0, sizeof(scene));
game->current_scene = pscene;
this way the memory will be allocated from the heap, surviving the exit from the function.
You will need later to free this memory once done with the object.
You also don't assign a value to scene->appearance when you are creating a new ghost. When you then try and print the appearence later you'll get whatever the pointer happens to point to printed ou.

Resources