Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of pointers to struct, only SIGSEGVs while debugging

The following code causes a SIGSEGV, but only while debugging.

#include <stdio.h>
#include <stdlib.h>

typedef struct enemy_desc
{
int type;
int x;
int y;
}enemy;

int main()
{
    enemy **enemies;
    enemies=(enemy **)malloc(sizeof(enemy *)*16);

    enemies[0]->type=23;

    printf("%i",enemies[0]->type);
    return 0;
}
like image 504
Ryan S Avatar asked Mar 15 '26 23:03

Ryan S


1 Answers

You are only creating space for 16 pointers to enemy, but are not creating the actual enemy objects that you're attempting to use.

Here is an example where I create an enemy object to the first pointer in the array.

#include <iostream>

typedef struct enemy_desc
{
int type;
int x;
int y;
}enemy;

using namespace std;
int main(int argc, char **argv)
{
    enemy **enemies;
    enemies=(enemy **)malloc(sizeof(enemy *)*16);
    memset(enemies, 0, sizeof(enemy*)*16);

    enemies[0] = (enemy *) malloc(sizeof(enemy));
    memset(enemies[0], 0, sizeof(enemy));

    enemies[0]->type=23;
    printf("type: %i  x: %i  y: %i\n\n",enemies[0]->type, enemies[0]->x, enemies[0]->y);

    enemies[0]->x = 10;
    enemies[0]->y = 25;
    enemies[0]->type= 7;
    printf("type: %i  x: %i  y: %i\n\n",enemies[0]->type, enemies[0]->x, enemies[0]->y);

    free(enemies[0]);
    free(enemies);
    return 0;
}
like image 50
RC. Avatar answered Mar 18 '26 12:03

RC.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!