0

This code is a part of a bigger program. I want to create an array of structs. The struct contains two data types: char and char*, each of which gets an input from the user. I'm a rookie and not able to find my way through this. Please help.

Error generated: Segmentation Fault 11.

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

typedef struct {
    char ch;
    char str[20];
}typ;

typ* add(char* str, char ch);

int main(int argc, char const *argv[]){
    typ* arr;
    arr = (typ*)malloc(sizeof(typ));

    char* name;

    name = (char*)malloc(10);
    *(name + 0)= 'c';
    *(name + 1)= 'a';
    *(name + 2)= 'p';
    *(name + 3)= '\0';
    char c = 'k';

    arr = add(name, c);

    printf("%c\n", arr->ch );
    printf("%s\n", arr->str );

    return 0;
}

typ* add(char* str, char ch){
    typ tempo;
    strcpy(str, tempo.str);
    printf("%s\n", str);
    tempo.ch = ch;
    typ* temp;
    *temp = tempo;
    return temp;
}
nalzok
  • 14,965
  • 21
  • 72
  • 139
hotessy
  • 1
  • 2

1 Answers1

2
  1. You used arr for the allocated memory, but then you assign it to add's return value, the memory got lost at this point, you have a memory leak.

  2. In the add function, you return a pointer to a variable with automatic storage, which does not exists after the function returns. That's why you are getting a segfault.

So I would allocate the struct in the add function, and returns it:

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

typedef struct {
    char ch;
    char str[20];
} Item;

Item* add(char* str, char ch);

int main(int argc, char const *argv[]){
    int i;
    int n = 3; // number of elements in the array
    Item** arr = malloc(n * sizeof(Item*));

    arr[0] = add("cap", 'k');
    arr[1] = add("foo", 'i');
    arr[2] = add("bar", 'j');

    printf("%c\n", arr[0]->ch );
    printf("%s\n", arr[0]->str );

    for (i = 0; i < n; i++)
         free(arr[i]);
    free(arr);
    return 0;
}

Item* add(char* str, char ch) {
    Item *i = malloc(sizeof *i);
    strcpy(i->str, str);
    i->ch = ch;
    return i;
}
fluter
  • 13,238
  • 8
  • 62
  • 100
  • Thanks @fluter. But it works fine even when I allocate memory to `arr`. The only change that i have to do then is `arr[0] = add(name, c);`. – hotessy Apr 09 '16 at 12:07
  • @DivyanshuSharma that leads to memory leak, as I said. – fluter Apr 09 '16 at 13:26
  • @fluter then how can I create the array of structs I originally wanted to? If I consider memory leakage, your code will only help me store one `Item` in `arr`. – hotessy Apr 09 '16 at 20:42
  • @hotessy see the change above, now you have an array of pointers to structs, and each element point to a struct that returned by add. Is this what you meant to do? – fluter Apr 09 '16 at 22:54