Segmentation Fault na strcat()

Asked

Viewed 59 times

2

Recently I started learning about function strcat() and developed the code below, but I’m encountering a Segmentation fault:

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

int main(void){
   char a[] ="sweet ";
   char b[] = "home ";
   char c[] = "alabama ";

   strcat(a, b);
   strcat(a, c);

   printf("%s", a);
  return 0;
}

Why does this mistake happen? How to avoid it?

1 answer

2


Almost everything you want to know is in:

Follow the links contained in them.

In short, you are trying to write to a memory protected area. The value of the variable a points to a static memory address, that is, that cannot be written, which is where all literals stand string. Those texts you used don’t stay in stack or in the heap which are the places where you can write something. To use the function strcat() need to provide a place where the destination can be written.

To avoid error you should create a memory area on the stack or on heap that fits the text you want to put and then copy the data you want there, as other questions have been asked and answered.

  • Ok, thank you so much for the answer will help a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.