I am trying to print out hello fred and I managed only to print out hello. what change do I need to make to print fred too.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//
// A short program to print the string "Hello, Fred"
//

int main (int argc, const char *argv[])
{
	char name[5];
	char ch = name[5];

	char *last_char = &name[5];
	ch = *last_char;

	char *src = "Fred";
	char *dst;
	dst = name;

	// copy the name
	while (*src)
	{	
                src != 0;
                ++src;
                *dst = *src;
	}


	char *msg = (char *) malloc (5);
	strcpy (msg, "Hello, ");
	strcat (msg, name);
	puts(msg);

	//free (last_char);
	free (msg);
	*last_char = 'A';

       //free (msg);
	msg = (char *) malloc (5);
	msg = src;

	puts (msg);
	return 0;
}

Initially, the first problem is that you are forgetting/didn't know that
if you declare an array of size 5 e.g. char name[5]; then that gives you memory locations name[0] to name[4]. But does not give you name[5] that can be used by the program for something else.

I have just reposted you code, without fixing it but adding a few comments about what is going wrong.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//
// A short program to print the string "Hello, Fred"
//

int main (int argc, const char *argv[])
{
  char name[5];
  char ch;
  char *src = "Fred";
  char *dst;
  dst = name;
  
  // copy the name
  while (*src)
  {	
    src != 0;    // Doesn't do anything
    ++src;       // Increment source before coping first name 
    *dst = *src; // set first character of dst to be 'r' then 'e' etc.
  }
  // dst is now 0. thus nothing in its string.

  
  char *msg = (char *) malloc (5);
  strcpy (msg, "Hello, ");  // memory leak since msg is only 5 long and 
                            // " hello, " is 7 (including 0 on end). 
  strcat (msg, name);       // More memory probelms / leak
                            // This puts msg into NAME.
  puts(msg);
  
  //free (last_char);
  free (msg);                
  
  //free (msg);
  msg = (char *) malloc (5);
  msg = src;                // This losses the memory allocated in line above.
  
  puts (msg);
  return 0;
}

hope it helps

I only read this quickly and I have a hard time understanding why this is only five bytes char *msg = (char *) malloc (5); Since copy "Hello, " to it then you strcat "Fred" to it

I only read this quickly and I have a hard time understanding why this is only five bytes char *msg = (char *) malloc (5); Since copy "Hello, " to it then you strcat "Fred" to it

Your malloc has size 5, but your string has a size of 7
your malloc goes from 0 to 4 (0,1,2,3,4)=5
H - E - L - L - O - , -\0 = 7
your malloc should be able to allocate all the character of your string plus the "\0"

Edited 7 Years Ago by Samyx: n/a

This article has been dead for over six months. Start a new discussion instead.