2.4 型付きバッファのサイズの変更

tpalloc()で割り当てられたバッファのサイズを変更するには、次のようにtprealloc(3c)関数を使用します:

char* tprealloc(char *ptr, long size)

次の表は、tprealloc()関数の引数を示しています。

表2-3 tprealloc()関数の引数

引数 説明
ptr サイズを変更するバッファを指すポインタ。このポインタは、tpalloc()の呼出しで設定されます。それ以外の方法で設定されている場合、呼出しは失敗し、tperrno(5)TPEINVALに設定されて、無効な引数がこの関数に渡されたことが示されます。
size 変更後のバッファ・サイズを指定する長精度型(long)。

tprealloc()が返すポインタは、元のバッファと同じタイプのバッファを指します。バッファの場所が変わっている場合があるので、返されたポインタを使用してサイズが変更されたバッファを参照します。

バッファのサイズを増やすためにtprealloc()関数を呼び出すと、バッファに新しい領域が割り当てられます。バッファのサイズを減らすためにtprealloc()関数を呼び出すと、実際にバッファのサイズが変更されるのでなく、指定されたサイズを超える領域が使用不能になります。型付きバッファの内容には影響しません。未使用領域を解放するには、必要なサイズを持つ別のバッファにデータをコピーし、未使用領域を持つバッファを解放します。

tprealloc()関数は、エラーが発生するとNULLポインタを返し、tperrnoに適切な値を設定します。エラー・コードについては、『Oracle Tuxedo ATMI C関数リファレンス』tpalloc(3c)に関する項を参照してください。

警告:

tprealloc()関数がNULLポインタを返した場合、内容が変更されて有効ではなくなったバッファが渡された可能性があります。

次のリストは、STRINGバッファの領域を再度割り当てる方法を示しています。

バッファのサイズ変更のリスト

#include <stdio.h>
#include “atmi.h”

char instr[100]; /* string to capture stdin input strings */
long s1len, s2len; /* string 1 and string 2 lengths */
char *s1ptr, *s2ptr; /* string 1 and string 2 pointers */

main()

{

(void)gets(instr);             /* get line from stdin */
s1len = (long)strlen(instr)+1; /* determine its length */

join application

if ((s1ptr = tpalloc(“STRING”, NULL, s1len)) == NULL) {
fprintf(stderr, “tpalloc failed for echo of: %s\n”, instr);
leave application
exit(1);
}
(void)strcpy(s1ptr, instr);

make communication call with buffer pointed to by s1ptr

(void)gets(instr);        /* get another line from stdin */
s2len = (long)strlen(instr)+1; /* determine its length */
if ((s2ptr = tprealloc(s1ptr, s2len)) == NULL) {
  fprintf(stderr, “tprealloc failed for echo of: %s\n”, instr);
  free s1ptr's buffer
  leave application
  exit(1);
}
(void)strcpy(s2ptr, instr);

make communication call with buffer pointed to by s2ptr
 . . .
}

次のリストは前述の例を拡張したもので、発生する可能性があるすべてのエラー・コードを確認する方法を示しています。

tprealloc()のエラーの確認のリスト

. . .
if ((s2ptr=tprealloc(s1ptr, s2len)) == NULL)
  switch(tperrno) {
  case TPEINVAL:
    fprintf(stderr, "given invalid arguments\n");
    fprintf(stderr, "will do tpalloc instead\n");
      tpfree(s1ptr);
if ((s2ptr=tpalloc("STRING", NULL, s2len)) == NULL) {
  fprintf(stderr, "tpalloc failed for echo of: %s\n", instr);
leave application
exit(1);
}
break;
case TPEPROTO:
   fprintf(stderr, "tried to tprealloc before tpinit;\n");
   fprintf(stderr, "program error; contact product support\n");
     leave application
    exit(1);
case TPESYSTEM:
   fprintf(stderr,
     "ORACLE Tuxedo error occurred; consult today's userlog file\n");
      leave application
  exit(1);
case TPEOS:
   fprintf(stderr, "Operating System error %d occurred\n",Uunixerr);
   leave application
   exit(1);
default:
fprintf(stderr,
"Error from tpalloc: %s\n", tpstrerror(tperrno));
break;
}