2

I just started learning the programming language C and am having a problem while solving 1 exercise below.

Write a program that dynamically allocates 10 bytes of memory for a pointer, with the provided function template as follows: bool allocate10Bytes(uint8_t *outPtr);

  • outPtr: output pointer
  • return: true: If the allocation is successful. false: If the allocation failed.

I tried with the following code but the pointer in main function is still not allocated.

bool allocate10Bytes(uint8_t* outPtr)
{
    outPtr = (uint8_t*)malloc(10 * sizeof(uint8_t));

    if (outPtr == NULL) {
        return false;
    }

    return true;
}

int main(void)
{
    uint8_t* p = NULL;

    bool success = allocate10Bytes(p);
    
    if (success) free(p);
    return 0;
}

Please help me. Thank you very much!

rawrex
  • 4,044
  • 2
  • 8
  • 24
Justin
  • 55
  • 3

1 Answers1

6

Your code aimed to change a pointer argument's value since arguments are passed by value, the code have changed the local value outPtr's value, not the one in main

To pass a pointer as an argument and change the pointer's value in callee, we have only one choice in C : to pass a pointer to the pointer


bool allocate10Bytes(uint8_t** outPtr) {
  *outPtr = malloc(10 * sizeof(uint8_t));

  if (*outPtr == NULL) {
    return false;
  }

  return true;
}

int main(void) {
  uint8_t* p = NULL;

  bool success = allocate10Bytes(&p);

  if (success) free(p);
  return 0;
}

For code smells: it's bad to use a magic number 10 in the code, it would be much better to add a macro or constant here.


If the function prototype must be bool allocate10Bytes(uint8_t* outPtr), then we need some ugly casting here. I don't think it's a good exercise problem, maybe your teacher is doing something wrong.

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
bool allocate10Bytes(uint8_t* outPtr) {
  uint8_t** outPtr1 = (uint8_t**)(outPtr);
  *outPtr1 = malloc(10 * sizeof(uint8_t));

  if (*outPtr1 == NULL) {
    return false;
  }

  return true;
}

int main(void) {
  uint8_t* p = NULL;

  bool success = allocate10Bytes((uint8_t*)&p);

  if (success) free(p);
  return 0;
}
prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42