Cooler_

sobre alocação em C

Mar 30th, 2012
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. /*
  2.  *by Cooler_
  3.   c00f3r[at]gmail[dot]com
  4.  
  5.   gcc -o code code.c; ./code
  6.  
  7.   professor de estrutura de dados
  8.  falo que não tinha como usar ponteiro
  9.  para reter uma string sem usar malloc()
  10.  bom tem milhares de formas sem malloc()
  11.  olhem algumas xD
  12.  
  13.   */
  14. #include <unistd.h>
  15. #include <string.h>
  16. #include <alloca.h>
  17.  
  18. void main(void)
  19. {
  20. //1 memset()  
  21.  char *x;
  22.  
  23. // \0 nullbyte para evitar bug :-X
  24.  memset(&x,'\0',4);
  25.  memset(&x,'o',3);
  26.  memset(&x,'l',2);
  27.  memset(&x,'a',1);
  28.  puts(&x);
  29.  
  30.  
  31.  
  32. //2 usando  sbrk()
  33. // sizeof(char)*4 == 1byte X 4, cada byte para uma letra e sobra uma para null byte
  34.  char *z=(char *)sbrk(sizeof(char)*4);
  35.  z="omg";
  36.  puts(z);
  37. // subtrair a memória para desalocar  "man sbrk"
  38.  z=(char *)sbrk(-sizeof(char)*4);
  39.  
  40.  
  41.  
  42. //3 usando STACK inves da HEAP para alocar na memória
  43.  char *y=(char *)alloca(sizeof(char)*4);
  44.  y="yes";
  45.  puts(y);
  46. // não precisa dar free() pois he STACK
  47.  
  48.  
  49.  
  50.  
  51. //4 apontando para um array de char
  52.  char string[4];
  53.  char *ptr=string;
  54.  ptr="foo";
  55.  puts(ptr);
  56.  
  57. // tem mais formas como calloc()...
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment