researcher
researcher

Reputation: 143

strcat in C error segmentation

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

int main() {
  char tab[2]={"12"};
  FILE *outfile;
  char *outname = "/home/dir/";
  printf("%s", strcat(outname,tab));
  outfile = fopen(strcat(outname,btab), "w");
  if (!outfile) {
    printf("There was a problem opening %s for writing\n", outname);
  }
}

I have this error: Segmentation Fault.

How can I fix it?

Upvotes: 0

Views: 1299

Answers (4)

Madara
Madara

Reputation: 163

In your code,

char *outname = "/home/dir/";

outname is a string literal and hence when used with strcat, it does not have enough length to hold the concatenated string.This results in segmentation fault.

Same is the case had you declared it as below,

char outname[] = "/home/dir/";

The solution for this to declare the size of the outname big enough to hold the concatenated string.

char outname[80] = "/home/dir/";

Upvotes: 0

user529758
user529758

Reputation:

At least two errors:

char tab[2] = {"12"};

You'd better use tab[3] or even better tab[] -- you need one extra char for the terminating NUL character.

Also,

char *outname = "etc...";

creates a constant string in the data segment of the executable -- it can't be overwritten, since strcat is using its first parameter to concatenate the two strings. So when strcat() tries to do so, it segfaults. Use

char outname[50]; // something big enough
strcpy(outname, "/home/dir");

instead.

Upvotes: 1

Umer Farooq
Umer Farooq

Reputation: 7486

outname is Const pointer so once you have entered some thing in it, you can't modify it.

However if you want to copy things in it, make a char array of the size equal to tab[] array because here the size of string to be copied is known. Most of the time char pointers like OUTNAME are used when you are taking input from a user once and you don't know how long that input will be.

Upvotes: 0

ouah
ouah

Reputation: 145879

outname is a string literal and string literals are not modifiable. Modifying a string literal is undefined behavior.

Upvotes: 1

Related Questions