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;
}

Dani AI

Generated

Several separate bugs combine to produce the symptoms seen in the original post: out-of-bounds access, a bad copy loop that skips the first character, incorrect allocation sizes, writing to memory you do not own, and leaking or reusing freed allocations. was right to call out indexing (an array declared char name[5] has elements name[0]..name[4] — do not dereference name[5]), and / correctly flagged the malloc(5) that can’t hold "Hello, " plus a terminator. See the C array rules and the string functions for details: and https://en.cppreference.com/w/c/string/byte/strlen.

Fix checklist

  • Compute allocation sizes with strlen(a) + strlen(b) + 1 (for the NUL).
  • Do not read or write array[N] for an array[N] declaration — that is one-past-end and UB.
  • Copy correctly and ensure the destination is NUL-terminated; the original loop increments the source before copying and never writes the terminator.
  • Check malloc return values and do not free memory twice or write through pointers to freed storage.

Example (minimal, different from the posted snippets) showing a safe approach:

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

int main(void) {
    const char *who = "Fred";
    char name_copy[sizeof "Fred"];           /* sizeof includes the NUL */
    memcpy(name_copy, who, sizeof name_copy);

    const char *greet = "Hello, ";
    size_t len = strlen(greet) + strlen(name_copy) + 1;
    char *msg = malloc(len);
    if (!msg) return 1;
    snprintf(msg, len, "%s%s", greet, name_copy);
    puts(msg);
    free(msg);
    return 0;
}

Further reading: malloc usage and string function docs at https://en.cppreference.com/w/c/memory/malloc and snprintf details at https://en.cppreference.com/w/c/io/fprintf#snprintf.

Recommended Answers

All 3 Replies

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"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.