This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Malloc is creating fault

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

  • When malloc(len) is called the first time, len has the value 0.  You'll always get NULL back from that call.

    Thanks and regards,

    -George

  • Hi George,

    In the code instead of  char *dest = (char *) malloc(len); I tried with char *dest = (char *) malloc(4); than also it is creating fault.

    Also len is more than 0 in print statement above doing malloc().

    Thanks,

    Bhavesh

  • I don't think your code really crashes in the malloc call. It looks like you pass uninitialized strings to strlen and such, which may block for a very long time and will return bogus results. (In particular, you store up to n characters in gStr (a buffer of n bytes), so there's no null termination at the end).

    You'll have to step through your code with a debugger and see where results don't match your expectations.

    EDIT1: your code may also run beyond the end of the input string pcBuf, unless it's always correctly formatted (which, as a suggestion, you should never assume). The simplest example for that is pcBuf = "{".

    EDIT2: your call to realloc is definitely wrong. realloc expects the new total length of a buffer, not an increment.

    EDIT3: I suggest you write a (or use an existing) small "string" library ( e.g. struct MyString { size_t length; char *buffer; } and accompanying functions) and test that in isolation. Then you go on writing the string manipulation code.


    EDIT4:  if(len >= strlen(gStr)); is almost certainly not what you wanted to write.

  • Bhavesh Patel said:
    I tried with char *dest = (char *) malloc(4); than also it is creating fault.

    Check and make sure you have allocated enough memory for the heap.  This is configured with the linker option --heap_size=number_of_bytes .

    Bhavesh Patel said:
    Also len is more than 0 in print statement above doing malloc().

    The UARTprintf call does not change the value of len.  It only takes the value of len as an input.

    Thanks and regards,

    -George

  • Markus/George,

    Able to find the solution by updating string pointer.
    Issue was null terminator for string was not recognized and was not able to initialize second string properly. So malloc() was allocating for second pointer.

    Thanks for the answers.

    Thanks,
    Bhavesh