Answers for "malloc()"

C++
4

malloc in c

#include <stdlib.h>

void *malloc(size_t size);

void exemple(void)
{
  char *string;
  
  string = malloc(sizeof(char) * 5);
  if (string == NULL)
    return;
  string[0] = 'H';
  string[1] = 'e';
  string[2] = 'y';
  string[3] = '!';
  string[4] = '';
  printf("%sn", string);
  free(string);
}

/// output : "Hey!"
Posted by: Guest on March-03-2020
1

malloc() in c and c++

/* malloc example: random string generator*/
#include <stdio.h>      /* printf, scanf, NULL */
#include <stdlib.h>     /* malloc, free, rand */

int main ()
{
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='';

  printf ("Random string: %sn",buffer);
  free (buffer);

  return 0;
}
Posted by: Guest on September-19-2020
0

C malloc

#include <stdlib.h>
int main(){
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */
    if (ptr != NULL) {
      *(ptr + 5) = 480; /* assign 480 to sixth integer */
      printf("Value of the 6th integer is %d",*(ptr + 5));
    }
}
Posted by: Guest on August-28-2021
1

Malloc

ptr = malloc(size); //You dont need to cast
Posted by: Guest on June-18-2020
0

malloc in c

int main(int argc, char *argv[])
{
    int* string = NULL;

    memoireAllouee = malloc(sizeof(int));
    if (string == NULL) 
    {
    	return;
   		string[0] = 'H';
        string[1] = 'e';
        string[2] = 'y';
        string[3] = '!';
        string[4] = '';
        printf("%sn", string);
    }



    return 0;
Posted by: Guest on April-27-2021
0

what is the use of malloc in c

In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.
Posted by: Guest on July-08-2020

Browse Popular Code Answers by Language