How to return a pointer to a dynamically allocated String, declared within a function?

Asked

Viewed 36 times

0

//Função de inversão de String.

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

#define SIZE 30

char* invertStr(char *source)
{   
    int size = strlen(source);
    
    char *inverted = malloc(sizeof(source) * (size + 1));

    int count = size;

    for (int i = 0; i < size; i++)
    {
        inverted[i] = source[count];
        count--;
    }
    inverted[size + 1] = ('\0');

    return inverted;
}

int main(void)
{
    char str[SIZE];
    char str2[SIZE];

    scanf("%29s", str);

    char *inverted = invertStr(str);

    if (inverted == 0)
    {
        printf("NULL Pointer. Memory alocation error");

        return -1;
    }

    strcpy(str2, inverted);

    printf("%s | %s\n", str, str2);

    free(inverted);

    return EXIT_SUCCESS;
}

The output of the second string is not displayed successfully.

Code running on ideone.

1 answer

1


  1. You’re allocating too much space. sizeof(source) is different from the size of sizeof(*source).
  2. You’re starting to write on top of \0 => count = size - 1;
  3. Is writing the \0 outside the allocated limit => inverted[size] = '\0';
char* invertStr(char *source)
{   
    int size = strlen(source);
    
    char *inverted = malloc(sizeof(*source) * (size + 1));

    int count = size - 1;

    for (int i = 0; i < size; i++)
    {
        inverted[i] = source[count];
        count--;
    }
    inverted[size] = '\0';

    return inverted;
}
  • Yet you are allocating too much space. I think it should be: char *inverted = malloc(sizeof(char) * (size + 1));

  • @anonimo I see no difference... *source == char. source is a pointer, will have 4 or 8 bytes depending on the architecture, *source is what source points out that in this case it is a char

  • The guy char takes 1 byte, and a pointer - as you said yourself - takes 4 or 8 bytes.

  • @anonymity source is a pointer. *source is a char.

  • @anonymity sizeof(char) and sizeof(*source)are equivalent. Thanks for the contribution, guys. Zero Based Arrays + Null Terminator confuse me a lot, I need to practice more, in addition to better understand the operation and operands of sizeof

Browser other questions tagged

You are not signed in. Login or sign up in order to post.