Question

I am running through some basic tutorials on C, using Code::Blocks.

Can anyone help me out with the following code, with some explanation? It builds but crashes when run.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_LEN 40

main()
{
   int pos;
   char *line,*aster,*blank;

   line=(char *)malloc(MAX_LEN);
   aster=(char *)malloc(1);
   blank=(char *)malloc(1);
   line="                                        ";
   aster="*";
   blank="";

   printf("Enter position of star (1-40): ");
   scanf("%d",&pos);

   if(pos>0&&pos<41)
   {
       printf("\n");
       printf("         1         2         3         4\n");
       printf("1234567890123456789012345678901234567890\n");
       puts(strcat(strncat(blank,line,pos-1),aster));
   }
   else
    printf("Out of range");
}

The problem seems to lie within the strcat line of code and I guess the use of pointers?

Was it helpful?

Solution

The problem is that your blank field provides space for one character, but you need up to 40 characters there. When using strcat or strncat, the destination buffer (which is the first argument to either function) must provide enough space for the concatenated string and a terminating \0 character.

What you want to do is something like

line = "                                        ";
blank = malloc(MAX_LEN+1); /* 40 characters + terminating '\0' */
blank[0] = 0; /* Needed for strcat to work */
[...]
puts(strcat(strncat(blank, line, pos-1), aster));

Another note: Your use of line and aster leads to a memory leak. If you want to fill the memory allocated with malloc with spaces, you should use memset, if you want to assign a string literal, you should not use malloc at all. What you actually do is overwriting the pointer returned by malloc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top