Hi,
I am writing a sample code where trying to parse a string. I have written a code which will split the string by some delimiter.
Now between this delimiter the size of the string is not same so I am trying to do malloc() with some size.
When I am doing malloc() it is creating fault and not able to identify the same.
Following are the functions:
void setSensorConfigParams(char *pcBuf) { int len=0, ses = 0; bool startRead = false; UARTprintf("\n Length of pcBuf : %d %s", strlen(pcBuf), pcBuf); char *gStr = (char *) malloc(1); if (gStr == NULL) { UARTprintf("Unable to allocate memory.\n"); exit(EXIT_FAILURE); } while((*pcBuf != NULL) && (*pcBuf != ']')){ // Checking weather Sensor channel characters received or no if(*pcBuf == '{'){ startRead = true; pcBuf++; } else if(*pcBuf == '}'){ startRead = false; if(strlen(gStr) > 2){ UARTprintf("\n gstrrrr-%s-%d", gStr, len ); /* char *deStr = (char *) malloc(len); // even here going to fault dest = memset(deStr, '\0', len); strncpy(deStr, gStr, len); */ splitUserString(gStr, ses, len); } ses++; len=0; } // Storing the data into other string if(startRead){ *(gStr+len) = *pcBuf; len++; if(len >= strlen(gStr)); gStr = (char *) realloc(gStr, 1); } pcBuf++; } free(gStr); } void splitUserString(char *str, int ses, int len) { char *token; int i = 0; UARTprintf("\n Length of str : %d %s-%d ", strlen(str), str, len); char *dest = (char *) malloc(len); // failing here. going to fault routine if(dest == null) // not coming to this line { UARTprintf("Unable to allocate memory.\n"); exit(EXIT_FAILURE); } dest = memset(dest, '\0', len); strncpy(dest, str, len); UARTprintf("\n Length of dest : %d %s", strlen(dest), dest); /* get the first token */ token = strtok(str, ","); /* walk through other tokens */ while( token != NULL ) { UARTprintf( "\n%d - %s", strlen(token), token); // Some of the code is removed token = strtok(NULL, ","); i++; } free(dest); }
I increased Heap Size from 4096 to 24576 and stack size from 1024 to 4096 but still it is giving fault.
Any idea while it is failing?
Thanks,
Bhavesh