THis is a program that splits a given string when it finds the
delimiter.
i.e this/is/a/boy/ delimiter is "/"
this
is
a
boy
i dont know what is the error but is alocated in split() function
can you help me guys?
Code:
#include<stdio.h>
#include<string.h>
#define MAXSPLITS 80
char **split(char *delimiter, char *str, int *cntp);
char *mem_alloc(char *buffer);
char *bufferAlloc,*buffer;
char **bufferSplits,**bufferAlcSpl;
int main (void){
char *inptStr,*delStr,**strArray;
int *countSplits=(int *)malloc(1 * sizeof(int));
//buffer for a given string
bufferAlloc=(char *)malloc(81*sizeof(char));
//buffer for the array that stores the splits
bufferAlcSpl=(char **)malloc(81*sizeof(char*));
if(bufferAlloc==NULL || bufferAlcSpl==NULL){
printf("MEMORY ALLOCATION ERROR");
exit(1);
}else{
buffer=bufferAlloc;
bufferSplits=bufferAlcSpl;
}
printf("\nEnter a string to split\n");
gets(buffer);
inptStr=mem_alloc(buffer);
strcpy(inptStr,buffer);
printf("\nEnter delimiter\n");
gets(buffer);
delStr=mem_alloc(buffer);
strcpy(delStr,buffer);
strArray=split(delStr,inptStr, countSplits);
return 0;
}
//dynamic memory allocation for the given strings
char *mem_alloc( char *buffer)
{
char *str;
str=(char *)malloc((strlen(buffer)+1)*sizeof(char));
if (!str){
fprintf (stderr, "Allocation error\n");
exit (1);
}
return(str);
}
//this is the buggy function
char **split(char *delimiter, char *str, int *cntp)
{
int counter=strlen(delimiter);
int i=0,j=0;
char *findDel;
char *strPtr=str;
for(i=0;i<MAXSPLITS;i++){
findDel=strstr(strPtr,delimiter);
if(findDel){
while(strPtr++<findDel)
{
bufferSplits[i][j] = *str++;
j++;
}
bufferSplits[i][j]='\0';
str+=counter;
strPtr+=counter;
}
}
for(i=0;bufferSplits[i];i++)
printf("\n%s\n",bufferSplits[i]);
}