realloc for (char **) doesn't seem to work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sieira
    New Member
    • May 2007
    • 31

    realloc for (char **) doesn't seem to work

    I have a list of strings, and a function which is supposed to add one in the tail of it.

    List is initialised this way:

    Code:
    char **Istate=NULL;
    
    Istate=malloc(sizeof (char *));
    Istate[0]=NULL;
    Function called like this (nIstate is an integer I'll use later in order to manipulate other lists):

    Code:
    nIstate=appendList(&Istate,buff);
    And finally, this is the function:
    Code:
    int appendList(char ***lst,char *str){
    	int i;
    	char **auxlst=NULL;
    		
    	for(i=0;*lst[i]!=NULL;i++);
    	
    	auxlst=realloc(*lst, (i+2)*sizeof (char *));
    	
    	if(auxlst==NULL){
    		fprintf(stderr,"La cagaste\n");
    		free(lst);
    		return -1;
    	}
    	*lst=auxlst;
    	
    	*lst[i]=malloc(strlen(str));
    	strcpy(*lst[i],str);
    
    	*lst[i+1]=NULL;
    
    	return i;
    }
    I can't understand why doesn't it work, it fails tryng to make *lst[i+i] point to NULL.

    Testing with gdb i've seen that strcopy works fine.

    First time I call the function, for loop finishes with i=0, so realloc gives space for two (char *).

    strlen(str) bytes are reserved for the first one, and the second one is supposed to point NULL, but then is when the program fails...

    Can anybody help me?. Thank you
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    I haven't looked at the whole code but this is not right:
    [quote=Sieira]
    *lst[i]=malloc(strlen( str));
    strcpy(*lst[i],str);
    [/code]

    Here you didn't allow for the null terminator and that means the allocation is one byte too small for the string so strcpy() corrupts memory.

    The code should be:
    [code=c]
    *lst[i]=malloc(strlen( str) + 1);
    strcpy(*lst[i],str);
    [/code]

    The other thing I notice is that you:
    Originally posted by Sieira
    *lst[i+1]=NULL;
    Apparently to denote the end of the array of strings. However, NULL is a valid null string, that is a "". Using this as an array terminator prevents using null strings within the array. You might use a specially coded string. Maybe "**end** or some such.

    Comment

    Working...