Help - builds, runs but crashes out at strcat

Hello all, my first post ::) ???


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?

Thanks,
Simon
The destination field blank is too small. Given that it is only one byte long, it has just enough room to store the null terminator, that is, a zero length string.

Attempting to do any string operation with a 1-byte field as the destination is bound to fail.

Also, rather than using the = operator here: aster="*"; you need the strcpy() function. Or just declare char aster[] = "*";

I think line should probably be the destination of your strcat operation.
Last edited on
Thanks Chervil. You were spot on with the blank pointer allocated length being too long, changed it for MAX_LEN+1.

I also encountered a problem when inserting "" into the pointers target as I now know this eliminates/overwrites the pointer address. I got around this by using blank[0]=0;

It compiled and worked following that. I didn't adjust aster. Its an early tutorial program, strcpy is upcoming so I will review that once I read through it.

Thanks again ;)
Topic archived. No new replies allowed.