“malloc” Réponses codées

malloc en 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] = '\0';
  printf("%s\n", string);
  free(string);
}

/// output : "Hey!"
Thurger

bases malloc

// Program to calculate the sum of n numbers entered by the user

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

int main() {
  int n, i, *ptr, sum = 0;

  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) malloc(n * sizeof(int));
 
  // if memory cannot be allocated
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);
  
  // deallocating the memory
  free(ptr);

  return 0;
}
Talented Tiger

malloc

// if you initialize a pointer and want to use it like an array, 
// you have to claim the space you use, 
// that is what the memory-allocation-funtion (malloc) does;

// exaple for that: str(0) belongs to you, but str(1), str(2), ... do not
// if you do not use the malloc funtion; 
// you can access it, but it could be used by another programm;

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

void func(void)
{
    char *str = malloc(sizeof(char) * 5); // sizeof --> char needs 
    // a specific space per value saved;
    // *5 --> 5 is the number of values in the array;

    char *str1 = malloc( 5 * sizeof *str1 );//      |
    char *str2 = malloc( sizeof(char[5]) );//       | other syntaxes

    if(str == NULL) { exit(1); } // malloc returns NULL 
    // if it could not allocate the memory;
    str[0] = 'H';
    *(str+1) = 'e';	// used like pointer
    str[2] = 'y';	// used like array
    *(str+3) = '!';
    str[4] = '\0';

    printf("%s\n", str);

    free(str); // frees the memory allocated to str;
    // if you free the memory too early and try to access str later
    // that is called a memory leak;
}

int main(void)
{
    func();
    return 0;
}

// shell: Hey!

// improved version of Thurger's
DannyTheTiger

Réponses similaires à “malloc”

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code