Simon
Simon

Reputation: 95

C - pointer to array of pointers

i have to store the pointers of a data structure. So, i need an array of pointer.

I created a simple example, but i receive a segmentation fault. Why i cannot do

buf->data[i] = pkt ??

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

#define MAX_SIZE    500000
#define MAX_CHAR    1024

char *string = "HelloHelloHello";

struct pkt {
    char *buf;
    int seq;
};

struct buffer {
    int a;
    int b;
    struct pkt **data;
};


struct buffer *new_buffer() {
    struct buffer *new;

    new = malloc(sizeof(struct buffer) * MAX_SIZE);
    if (new == NULL) {
        perror("malloc(buffer)");
        exit(EXIT_FAILURE);
    }

    struct pkt *data;
    data = malloc(sizeof(struct pkt) * MAX_SIZE);
    if (data == NULL) {
        perror("malloc(data)");
        exit(EXIT_FAILURE);
    }

    new->data = &data;

    new->a = 0;
    new->b = 0;

    return new;
}

struct pkt *new_pkt(char *data, int seq) {
    struct pkt *pkt;

    pkt = malloc(sizeof(struct pkt));
    if (pkt == NULL) {
        perror("malloc(pkt)");
        exit(EXIT_FAILURE);
    }

    pkt->buf = malloc(sizeof(char) * MAX_CHAR);
    if (pkt->buf == NULL) {
        perror("malloc(pkt->buf)");
        exit(EXIT_FAILURE);
    }

    strncpy(pkt->buf, data, MAX_CHAR);
    pkt->seq = seq;

    return pkt;
}

void add_pkt(struct pkt *pkt, struct buffer *buf, int i) {
    buf->data[i] = pkt;  //segmentation fault
}


int main() {
    struct buffer *my_buffer = new_buffer();
    struct pkt *pkt;
    int i;

    for(i=0; i<MAX_SIZE; ++i) {
        pkt = new_pkt(string, i);
        add_pkt(pkt, my_buffer, i);
        printf("[%d]", i);
    }

    return 0;
}

Upvotes: 2

Views: 83

Answers (1)

mch
mch

Reputation: 9804

change

struct pkt *data;
data = malloc(sizeof(struct pkt) * MAX_SIZE);
if (data == NULL) {
    perror("malloc(data)");
    exit(EXIT_FAILURE);
}

new->data = &data;

to

new->data = malloc(sizeof(struct pkt*) * MAX_SIZE);
if (new->data == NULL) {
    perror("malloc(new->data)");
    exit(EXIT_FAILURE);
}

struct pkt *data; is a local variable, saving its address and using it after the scope ends, is undefined behaviour. Also you want a memory area where you can save some struct pkt*s and not struct pkts.

Since you are not freeing anything, you have a big memory leak.

Upvotes: 2

Related Questions