c - dynamic strings in struct -
i having problem understanding concept of dynamic memory allocation, have code encountering segfault perhaps 1 may have insight?
#include <stdio.h> #include <stdlib.h> typedef struct tname { char **stringa; int capacity; } tname; tname *createtname(int length); tname *destroytname(tname *l); int main(void) { tname *ll = createtname(10); } tname *createtname(int length) { tname *temp; int i; temp->capacity = length; temp->stringa= (char**) malloc(sizeof(char*) * length); for(i=0;i<length;i++) temp->stringa[i] = (char*) malloc(sizeof(char)*50); return temp; }
when call run program segfault, can assist me please?
your problem here:
temp->capacity = length;
you asigning value variable, doesn't have memory yet. have allocate memory struct to.
use this:
tname *temp = malloc( sizeof(tname) );
if write tname *temp
, compiler allocate 4 bytes (or 8 in 64bit systems) pointer. wont't allocate momory, pointer pointing to.
another problem @ malloc, allocates memory string - should this:
temp->stringa = malloc(length+1);
fist of all, don't have multiply sizeof(char*)
(which again 4 or 8 bytes), sizeof(char)
. variabletype char
needs 1 byte, don't have mulitply @ all.
but must not forget allocate 1 extra-byte string, if want use string-operations. byte needed stroe ascii-0, specifies end of string.
if forget byte, program can result in strange output, , in sefgaults.
and loop:
for(i=0;i<length;i++) temp->stringa[i] = (char*) malloc(sizeof(char)*50);
i don't know want achieve it, can add more information?
Comments
Post a Comment