Thread: C memory allocation ( malloc ) issue - strange characters on the console

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    9

    C memory allocation ( malloc ) issue - strange characters on the console

    Hi Guys,

    Greetings you in the forum! I would like to use char array manipulations instead of using strcpy/strcat methods.

    So I created a C function which require a char array as an input parameter and it returns with the new char array ( which contains the input parameter 3 times succesively )

    After running the program I got some bizarre, strange characters on the console: The result: dogsdogsdogsh=C:zńĹKÄ☺
    It is a bit disturbing for me... What do you think, which would be my problem? What is the background of the correct memory allocation ?

    Any help would be appreciated! Very thx for your help!

    Here is my code snippet, you can run it ( I use DevCpp ):

    Code:
    #include<stdio.h>
    char *WriteParamStr3Times(char* paramStr); // the prototype of the function
    main()
    {
    	// define maximum 10 long string
    	char myString[10]="dogs";		
    	
    	// call the function which writes the parameter 3 times successively
    	char *resultString = WriteParamStr3Times(myString);		
    	
    	// write result string
    	printf("The result: %s", resultString);
    }
    
    
    // try to write 3times in consecutive mode
    char *WriteParamStr3Times(char* paramStr)
    {	
    	char *lokalStr = (char *) malloc(strlen(paramStr)*3); // allocate memory 3x the parameter string
    	int i, j;		
    	for (i=0, j=0; i< strlen(paramStr)*3; i++, j++)				
    		{
    			if( j == strlen(paramStr))  // when paramStr finished, starting again
    			{				
    				j=0;
    			}
    			lokalStr[i]	= paramStr[j];	
    		}			
    	return lokalStr;
    }
    Last edited by Puli; 11-20-2018 at 03:54 PM.

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Add at least one more char to the malloc'd memory for the Nul byte at the end.
    Null terminate the array before returning the pointer on line 29. Otherwise you are printing out whatever garbage is in memory until printf() finds a Nul byte in memory.
    Code:
    ...
    lokalStr[i] = '\0';
    return lokalStr;
    Also, don't cast the return from malloc(). Not needed, unless you are using a VERY OLD compiler!
    Last edited by rstanley; 11-20-2018 at 04:54 PM.

  3. #3
    Registered User
    Join Date
    Nov 2018
    Posts
    9
    Hi stanley,

    Very thanks for your detailed help!
    I have read about the last closing '\0' symbol, and I understood your remark. I have to close the the literal, else these garbages are displayed in my string.

    It works without any problem, and I don't need to cast the malloc
    Very thx again!

    Code:
    char *WriteParamStr3Times(char* paramStr)
    {   
        char *lokalStr = malloc(strlen(paramStr)*3); // allocate memory 3x the parameter string
        int i, j;       
        for (i=0, j=0; i< strlen(paramStr)*3; i++, j++)              
            {
                if( j == strlen(paramStr))  // when paramStr finished, starting again
                {               
                    j=0;
                }
                lokalStr[i] = paramStr[j];  
            }           
        lokalStr[i] = '\0';
        return lokalStr;
    }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You need
    char *lokalStr = malloc(strlen(paramStr)*3+1); // allocate memory 3x the parameter string
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Nov 2018
    Posts
    9
    Hi Salem,
    Very thx for your useful remarks, then I tried to test my program using max length of the parameter string.


    Code:
    char myString[10]="dogs_cats";    // this means:  'd' 'o' 'g 's' '_' 'c' 'a' 't' 's' '/0'

    As I imagine the size of the memory allocation needs 3 times of the length string ( 'd' 'o' 'g 's' '_' 'c' 'a' 't' 's' '/0' - the string contains the closing literal ) and additionally the closing character for the end ( '\0')


    Code:
    #include<stdio.h>
    char *WriteParamStr3Times(char* paramStr); // the prototype of the function
    main()
    {
        // define maximum 10 long string
        char myString[10]="dogs_cats";    // 'd' 'o' 'g 's' '_' 'c' 'a' 't' 's' '/0'    ->  this is the max length of the characters
        
        // call the function which writes the parameter 3 times successively
        char *resultString = WriteParamStr3Times(myString);        
        
        // write result string
        printf("The result: %s", resultString);
    }
    
    
    // try to write 3times in consecutive mode
    char *WriteParamStr3Times(char* paramStr)
    {    
        char *lokalStr = malloc(strlen(paramStr)*3); // allocate memory 3x the parameter string - Currently it works without any problem
        int i, j;        
        for (i=0, j=0; i< strlen(paramStr)*3; i++, j++)                
            {
                if( j == strlen(paramStr))  // when paramStr finished, starting again
                {                
                    j=0;
                }
                lokalStr[i]    = paramStr[j];    
            }            
        lokalStr[i]='\0';
        return lokalStr;
    }

    But with my ide ( DevCPP ) it works with the code (as attached above ) without increasing the allocation size of the 'lokalStr' +1. Is it necessary to allocate +1 unit for the string? But just to be on the safe side can we allocate memory for the last closing literal ('\0') ?
    Very thanks for your help!

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Congratulations, you've discovered there are things you can do wrong and it can still produce the right answer.

    But tomorrow, you can do exactly the same thing (maybe your strings are a bit longer), and it all blows up.

    Think about it.
    char mystring[2] = "a"; // 'a' + '\0'
    char mystring[4] = "aaa"; // 'a' + 'a' + 'a' + '\0'


    So why do you think
    char *resultString = WriteParamStr3Times("a"); // returns "aaa"
    needs only 3 characters, despite having a \0 on the end as well.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Nov 2018
    Posts
    9
    Hi Salem,
    Thank you very much for your answer, you were right. I continued tracking that problem deeply and I debugged my code because I would like to understand the mechanism of the allocation.

    Code:
    // define maximum 10 long string
        char myString[10]="dogs_cats";    // 'd' 'o' 'g 's' '_' 'c' 'a' 't' 's' '/0'     ->  10 char long string
              
    // some debugging info
        int f = strlen(myString);  // f = 9 -> "dogs_cats" instead of 10 :) 
        printf("lenth: %d", f);
    So, the strlen(myString) function gave me the "real" length of the string, then it is clear, why I should use the following allocation: malloc(strlen(paramStr)*3+1)
    We need to close the "real" concatenated string with the '\0' terminate literal.

    Thanks again!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help, Dynamic allocation of memory using malloc. C
    By Bryan Justo in forum C Programming
    Replies: 10
    Last Post: 04-29-2015, 10:28 PM
  2. malloc memory allocation
    By jamorp in forum C Programming
    Replies: 3
    Last Post: 10-17-2014, 06:57 AM
  3. Memory allocation with malloc
    By duif in forum C Programming
    Replies: 6
    Last Post: 11-28-2012, 09:05 AM
  4. Malloc printf with strange characters....
    By Gil Carvalho in forum C Programming
    Replies: 5
    Last Post: 06-18-2012, 02:09 PM
  5. Memory allocation without malloc
    By messi89 in forum C Programming
    Replies: 5
    Last Post: 05-30-2010, 07:27 AM

Tags for this Thread