Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Char pointer return wrong value with clang

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading