Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
I am writing a very simple program where I am trying to concatenate two string in a for loop. The first string in the string concatenation is fixed and the second string is obtained by using itoa funciton. The program is building up successfully but when I am trying to run the program then it is not able to run and getting stopped. I just debugged the program and while debugging I realized that the program is getting stuck in the string concatenation operation. I am posting the program below. Thanks for all your support :
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
char *str="NULL" ,dec[] = "NULL";
int i,num;
printf("Enter a number : \n");
scanf("%d",&num);
for (i=0;i<num;i++)
{ str = "test_file_num_";
itoa(i,dec,10);
strcat(str,dec);
printf("%s\n",str);
}
return 0;
}
Writing to
stris wrong, its memory is not accessible to write. When you do thischar *str="NULL"for starters you are merely allocating 5 bytes (you will need more when you start concatenating), and you are also doing it on read only memory (might be on .data or might be on .text), in some cases it will work but it is undefined behavior.If you can’t use dynamic memory try to do something like this instead:
This allocates 128 bytes on the stack (you might need more than that). It is not the best way to go, but it will be the smallest change that will fix your problem.
EDIT:
Same problem with this line
str = "test_file_num_";It points
strto a string literal that resides on read only memory. Change that for this:This will copy the string literal to the stack allocated buffer.
Finally, I think you should replace all the code inside the loop with simply this: