char형을 return하는 함수에서 동적할당 질문

Jason@Google의 이미지

#include <stdio.h>
#include <stdlib.h>
 
// 입력받은 영어 문자열을 모두 대문자로 리턴하는 프로그램
 
char* return_c(char* str)
{
	char* ptr = str;
 
	if (*ptr >= 'a' && *ptr <= 'z')
		return *ptr - ('a' - 'A');
	else
		return *ptr;
}
 
int main()
{
	char * str = malloc(sizeof(char) * 100);
 
	printf("영문의 문자열을 입력: ");
	gets_s(str, 100);
 
	for (char* ptr = str; *ptr != '\0'; ptr++) {
		printf("%c ", return_c(ptr));
	}
 
	free(str);
	return 0;
}
<code/>
 
char 형을 리턴할때는 값이 아닌 주소를 리턴하기 때문에 힙 영역애 할당해주지 않으면 지워져 버린다고 들었습니다. 위 코드처럼 main에서 할당하는 것도 의미가 있는건가요?  
그리고 반환형이 있는 함수 내에서 동적할당을 해주려면 free를 어디다 해줘야 하는지 모르겠어서
질문 남겨 봅니다.
라스코니의 이미지

그럴 경우에는 보통 init(), destroy() 등을 써 볼수 있습니다.

upper_init(char *str);
upper_do(char *str);
upper_destroy(char *str);

익명 사용자의 이미지

여러 가지 방법이 있습니다.

1. in-place로 동작한다.

원본이 있는 자리에 그대로 덮어써버리는 방법입니다.

만약 원본을 보존할 필요가 있다면 호출한 쪽에서 알아서 백업해 두면 되죠.
그럴 필요가 없다면, 불필요한 메모리 할당 및 해제 비용이 전혀 들지 않게 되는 장점이 있습니다.

2. 호출한 쪽이 알아서 적절한 타이밍에 free해 줄 것을 믿고, 새로 malloc한 메모리를 반환한다.

free 안 하면 memory leak 되는 거고요. 아무튼 난 잘못 없음.

3. 호출한 쪽이 반환값이 들어갈 메모리도 같이 제공하도록 한다.

strcpy가 그런 식으로 동작하지요.
만약 반환값이 들어갈 자리가 너무 좁다면 buffer overflow가 발생하게 됩니다. 아무튼 난 잘못 없음.

반환값 메모리 주소를 원본 문자열 주소와 같게 줄 경우 위 1번 방식과 동일하게 동작하도록 할 수도 있겠지요.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.