strcat()와 관련된 질문입니다.

ratmhun의 이미지

안녕하세요. 프로그래밍 초보입니다.
A Book on C 6장 43번 문제인데요.

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

int main(void)
{
  char *p1 = "abc", *p2 = "pacific sea";

  printf("%s    %s    %s\n", p1, p2, strcat(p1, p2));
  return 0;
}

예상한 결과는...

abc    pacific sea   abcpacific sea

그런데 이렇게 나오지 않고 세그멘테이션 오류가 발생하는 군요.
무엇이 문제인지 잘 모르겠습니다.

맹고이의 이미지

p1이 p2까지 담을 수 있는
충분한 공간이 있어야 되는 걸로
알고 있습니다...

exsider의 이미지

int main(void) 
{ 
  char *p1 = "abc", *p2 = "pacific sea"; 

  printf("%s    %s    %s\n", p1, p2, strcat(p1, p2)); 
  return 0; 
} 

strcat 를 쓰려면 덧붙여지는 문자열 (p1) 쪽에 충분한 공간이 있어야 합니다.
그런데 코드에서 공간을 선언하지 않고 포인터만 선언하였으므로 당연히 에러가 납니다.

char p1[80];  /*크기는 적당히 크게*/
char * p2 = "pacific sea"; 

strcpy(p1,"abc");
strcat(p1,p2);

이렇게 바꿔보세요.

ratmhun의 이미지

관심 가져주셔서 감사드립니다. 이걸 생각 못했네요.

char *strcat(char *s1, register const char *s2)
{
  register char *p = s1;

  while (*p != '\0')
    ++p;
  while (*p++ = *s2++) 
    ;
  return s1;
}

calloc() 혹은 malloc() 를 이용해서 p1의 크기를 잡아준 뒤에 p2를 붙이는 것도 가능하겠군요.

cskblue의 이미지

한글 맨페지에 보면

Quote:
dest문자열은 결과를 위해 충분한 공간을 가지고 있어야 한다

얼마나 충분해야하는지 처음쓰는사람은 모르겠네요;;;

ratmhun wrote:
char *p1 = "abc", *p2 = "pacific sea";

이렇게 쓰시면 되겠네요.
     char arr1[50] = "abc ";
     char arr2[] = "pacific sea";
     strcat(arr1, arr2);

혹은
     char *p1 = "abc ";
     char *p2 = "pacific sea";
     char *p3;

     p3 = (char *)malloc((strlen(p1) + strlen(p2) + 1) *sizeof(char));

     strcpy(p3, p1);
     strcat(p3, p2);
ratmhun의 이미지

답변 감사드립니다.
덕분에 strcpy()에 대해서 많은 것을 알게 되었습니다.

김충길의 이미지

일반적으로 아래의 코드가 컴파일 되면 "abc" 는 text 영역에 저장됩니다.
거기에 write를 할려고 했기 때문에 세그먼트폴트 난겁니다.

char p1[] = "abc", p2[] = "pacific sea";
라고 하면 예상했던 결과가 나옵니다.

ratmhun wrote:
안녕하세요. 프로그래밍 초보입니다.
A Book on C 6장 43번 문제인데요.
#include <stdio.h>
#include <string.h>

int main(void)
{
  char *p1 = "abc", *p2 = "pacific sea";

  printf("%s    %s    %s\n", p1, p2, strcat(p1, p2));
  return 0;
}

예상한 결과는...

abc    pacific sea   abcpacific sea

그런데 이렇게 나오지 않고 세그멘테이션 오류가 발생하는 군요.
무엇이 문제인지 잘 모르겠습니다.

screen + vim + ctags 좋아요~

partout의 이미지

김충길 wrote:
일반적으로 아래의 코드가 컴파일 되면 "abc" 는 text 영역에 저장됩니다.
거기에 write를 할려고 했기 때문에 세그먼트폴트 난겁니다.

char p1[] = "abc", p2[] = "pacific sea";
라고 하면 예상했던 결과가 나옵니다.

p1에 충분한 공간이 할당되어 있지 않기 때문에 여전히 문제가 있는 코드입니다.

어찌나 졸린지..~~

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.