2

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;
}
3
  • 1
    Maybe you should allocate memory to data . Commented Oct 24, 2015 at 11:30
  • I just did it, with data = malloc(sizeof(...)); and new->data = &data Commented Oct 24, 2015 at 11:54
  • 1
    No aparent debugging, DCV. Commented Oct 24, 2015 at 12:01

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.