I´m trying to execute a program where I return a char * using malloc with clang but it gives me some errors that with mingw it doesn´t give me.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *prueba(const char *);
int main(){
printf("%s\n", prueba("adedds"));
printf("%s\n", prueba("vxbc"));
printf("%s\n", prueba("ewefxx"));
printf("%s\n", prueba("asde"));
printf("%s\n", prueba("vbcvbcv"));
printf("%s\n", prueba("sded"));
}
char *prueba(const char *str){
char *str_return = malloc(strlen(str));
for (size_t i = 0; i < strlen(str); i++) str_return[i] = str[i];
return str_return;
}
The results with clang are these:
adeddsð
vxbc└
ewefxxð
asde└
vbcvbcv
sded└
The results with mingw are these:
adedds
vxbc
ewefxx
asde
vbcvbcv
sded
I´m newbie with this compiler so I don´t know what really happen
>Solution :
You forgot to zero terminate your strings
int len = strlen(str);
char *str_return = malloc(len + 1); <<<<== make space for 0
for (size_t i = 0; i < len; i++)
str_return[i] = str[i];
str_return[len] = 0; <<<<<======== set 0
return str_return;
simpler is
int len = strlen(str);
char *str_return = malloc(len + 1); <<<<== make space for 0
strcpy(str_return, str);
return str_return;
also strdup will do it in one got for you, it combines malloc and copy
return strdup(str);
and of course you should really check that malloc workd