LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   string in c - strcat causes segmentation fault (http://www.linuxquestions.org/questions/programming-9/string-in-c-strcat-causes-segmentation-fault-858578/)

Ranny 01-25-2011 10:50 AM

string in c - strcat causes segmentation fault
 
I am trying to concat strings, and probably doing something conceptually wrong. This code:
Code:

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

int main () {
const MAXL=256;
char *buffer; 
char *tmpch; 

buffer=malloc(MAXL*sizeof(char)); 
tmpch=malloc(MAXL*sizeof(char)); 

buffer="aaa";
tmpch="bb";
puts(buffer);
strcat(buffer,tmpch);

return 0;
}

compiled with gcc 4.4 on a Linux machine (Ubuntu), runs and gives a seg fault. Why?

Thanks!

dugan 01-25-2011 10:56 AM

Code:

buffer="aaa";
strcat(buffer,tmpch);

The first quoted line points buffer to a string constant.

The second line tries to overwrite the string constant.

You need to set the value of buffer with strncpy, not the assignment operator.

Ranny 01-25-2011 12:53 PM

Thanks! now it's working...

dugan 01-25-2011 12:58 PM

I should point out to you that:
  1. you have memory leaks, because the malloc'd memory is never freed
  2. to protect yourself from yourself, you should use strncat and not strcat


All times are GMT -5. The time now is 03:05 AM.