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

void *alloc_init(void *ptr, size_t size, void *val)
{
    ptr = malloc(size);
    memcpy(ptr, val, size);
    return ptr;
}

int main()
{
    int *a;
    int val = 5;
    int b = 5;
    alloc_init(a, 4, &val);
    printf("%d\n", *a);
    return 0;
}

It's a very simple program - I wanted to test the alloc_init function. I expect 5 to be printed, but it's always 1. The function should be allocating memory for a variable(in this case) and assigning it a value passed to the function by copying it's bytes. What am I doing wrong?

S.Sot
  • 321
  • 1
  • 7

1 Answers1

1

Two ways to do this (both untested):

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

void alloc_init(void **ptr, size_t size, void *val)
{
    *ptr = malloc(size);
    memcpy(*ptr, val, size);
}

int main()
{
    int *a;
    int val = 5;
    int b = 5;
    alloc_init(&a, sizeof *a, &val);
    printf("%d\n", *a);
    return 0;
}

or

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

void *alloc_init(size_t size, void *val)
{
    void *ptr = malloc(size);
    memcpy(ptr, val, size);
    return ptr;
}

int main()
{
    int *a;
    int val = 5;
    int b = 5;
    a = alloc_init(sizeof *a, &val);
    printf("%d\n", *a);
    return 0;
}

You should probably prefer the 2nd approach. Passing an int** where a void** is expected is probably UB.

William Pursell
  • 204,365
  • 48
  • 270
  • 300