ページ 11

mallocで文字が途切れる

Posted: 2017年11月06日(月) 03:29
by Ohagi

コード:

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

int main(int argc, char *argv[])
{
  char *str;
  char temp[128];
  int size;

  printf("array size = ");
  fgets(temp, sizeof(temp), stdin);
  size = atol(temp);
  
  str = malloc(size);

  
  printf("sizeof(str)  = %d\n", (int) sizeof(str));
  printf("sizeof(temp) = %d\n", (int) sizeof(temp));

  /* fgets(str, sizeof(str), stdin); */
  fgets(str, size, stdin);
  printf("str[] = %s\n", str);
  
  return 0;
}
$ ./a.out
array size = 14
sizeof(str) = 8
sizeof(temp) = 128
hello,world
str[] = hello,world


本当はコメントアウトしている fgets(str, sizeof(str), stdin); でstdinから文字列を受け取りたかったのですが
そうするとstr[] = hello,w で途切れてしまいました。
sizeofをprintfで確認すると普通に定義した文字列tempは128, mallocで取得したstrは8になりました。
8バイトというと、ポインタ変数のサイズなのだと思います。
ではsizeofでmallocで取得したアドレスサイズを取得するにはどう書けばできますか?
そのままsizeを書いてもプログラムは動くと思うのですが、sizeofで調べる方法が知りたいです。

Re: mallocで文字が途切れる

Posted: 2017年11月06日(月) 04:13
by みけCAT
「アドレスサイズ」の意味がよくわかりませんが、mallocで直接数値で指定して確保した領域の大きさをsizeofで取得するのは難しいと思います。
mallocで確保した領域の大きさは、malloc_usable_size関数か_msize関数で取得できるかもしれません。

malloc_usable_size(3) - Linux manual page
_msize

malloc_usable_size() - malloc()で確保したサイズを取得したい場合。 - sai’s diary
[故]ぶろぐ: mallocで確保したサイズを後から取得する。

Re: mallocで文字が途切れる

Posted: 2017年11月06日(月) 10:14
by Ohagi
あまりそういう使い方はしないのですね。
返信ありがとうございました。