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

Threaded View

Previous Post Previous Post   Next Post Next Post
  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.

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