0
void*ft_print_memory(void *addr, unsigned int size)
{
    char *memory;

    if (size == 0)
        return (addr);
    memory = (char *)addr;
    memory[16] = '\0'; // the error raise from this line
    return (addr);
}

I'm new to C programming and working with gcc on MacBook m1 Montery... Does the typecast create variable on stack or heap ? does the typecast create a valid string like malloc ?

called from main

int main (int argc, const char *argv[])
{
    char *str;

    str = "0123456789abcdefghijklmnopqrstuvwxyz";
    ft_print_memory(str, 16);
    return (0);
}
RoGKôT
  • 31
  • 6
  • This is the way of declaring the string in the main who make it works... the return value of ft_print_memory doesnt make difference. – RoGKôT Oct 30 '22 at 08:12
  • Ture Pålsson... Yes as litteral string are read-only... thanks !!! – RoGKôT Oct 30 '22 at 08:16
  • "Does the typecast create variable on stack or heap?" No, a typecast does not create any new variable at all. It only tells to compiler to treat one value of a certain type as if it was of a different type. That line assigns one value from a variable on stack or in a register to another local variable. It also only copies the address stored in that variable, not the memory where it points to. – Gerhardh Oct 30 '22 at 08:25

1 Answers1

0

For example, this variant works:

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

void ft_print_memory(void *, unsigned int);


int main (int argc, const char *argv[]){
    char str[64] = "0123456789abcdefghijklmnopqrstuvwxyz";
    ft_print_memory(str, 16);
 fprintf(stdout,"%s\n",str);
    return 0;
}

void ft_print_memory(void *addr, unsigned int size){
    char *memory;

    if (size == 0)        return ;
    memory = (char *)addr;
    memory[16] = '\0'; // the error raise from this line
//    return (addr);
}

  • I forgot to mention as student I only have right to use write... but it concern only output ? and the function ft_print_memory MUST be as I write... so return a void * But is this work because you remove the return or by the way you declare str in main ? – RoGKôT Oct 30 '22 at 07:59
  • I think because I declared str in main. You can print in ft_print_memory() too. But it is no the sense to return from subroutine an address, which you gives to it like argument. – Peter Irich Oct 30 '22 at 14:57
  • I know but it's like this my teacher protoype it !! – RoGKôT Oct 30 '22 at 19:42