void adicionaHashtag(char* x){
char*y=malloc(sizeof(x));/***ERROR IS HERE***/
int i;
for(i=0; i<strlen(x); i++){
y[i]=tolower(x[i]);
}
You're trying to allocate and initialize a string with a copy of the string pointed to by x
.
sizeof(x)
is the size of a char*
pointer. That's typically 4 or 8 bytes. You need to allocate enough space to hold the string itself.
char *y = malloc(strlen(x) + 1);
The + 1
is to allow for the terminating null character '\0'
.
Calling strlen
on each iteration of the loop is inefficient, but not incorrect; I'll leave that for now. There's a potential problem if any of the copied characters have negative values (an unfortunate characteristic of the tolower()
function. The assignment should be:
y[i] = tolower((unsigned char)x[i]);
Finally, let's say x
points to the string "hello"
. You're correctly copying 5 characters -- but not the final '\0'
. One possible fix is to change the <
in the loop condition to <=
, which will copy characters 0 through 5 rather than 0 through 4.
But you can just use the existing strcpy
function, which handles all this for you (and more efficiently):
char *y = malloc(strlen(x) + 1);
strcpy(y, x);
(You should also check the value returned by malloc
, and treat it as an error if it's NULL
.)
For that matter, you probably don't need y
at all. x
is already a pointer to a string. You copy it into the memory allocated for y
, and then you copy that into aux->nome
. Unless there's more code you haven't shown us that uses y
, this is unnecessary (and a memory leak!). You can drop the declaration of y
and the code that initializes it, and just copy from x
directly:
Lista_Hashtags *aux = malloc(sizeof *aux);
strcpy(aux->nome, x);
(This assumes that aux->nome
is an array, not a pointer, and that it's big enough to hold a copy of the string.)
(Note that I've changed your malloc
call to a simpler and more robust form.)