Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

419
Vistas
How to append a char to a String in C using a function

I was writing a lexical analyzer in which I need to append a char to a string (a char *). For some reason, the code below is resulting in string having a value of "(null)" when I print it to stdout. The function is given below.

void append_char(char *buffer, char c) {
  if(buffer == NULL) {
    buffer = malloc(sizeof(char));
    if(buffer == NULL) {
      fprintf(stderr, "COuld not allcocate memory to buffer\n");
    }
  } else {
    buffer = realloc(buffer, sizeof(buffer) + sizeof(char));
  } 
  buffer[sizeof(buffer) - 1] = c;
}

When I run the lines

 char *buf = NULL;
 append_char(buf, 'a');
 append_char(buf, '\0');
 printf("buffer: %s\n", buf);

it prints (null) to stdout. How can I fix this?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Pass by value

append_char(char *buffer, char c) does not affect the caller's buf in main(): append_char(buf, 'a');. buf remains NULL. This leads to OP's output.

Insufficient size

Insufficient size for the newly allocated string. No room for the null character.

Wrong size

With char *buffer, sizeof(buffer) is the size of a pointer, not the amount allocated beforehand.

Lost memoery

When buffer = realloc(buffer, sizeof(buffer) + sizeof(char)); fails (realloc() returns NULL) , the original value of buffer is lost. Save the result and test.

Note: OK to call realloc(NULL, ...).


char *append_char(char *buffer, char c) {
  size_t old_length = buffer ? strlen(buffer) : 0;
  size_t new_length = old_length + 1; // +1 for c
  // Size needed for a string is its length + 1
  char *new_buffer = realloc(buffer, new_length + 1); // +1 for \0
  if (new_buffer == NULL) {
    fprintf(stderr, "Could not allocate memory to buffer\n");
    free(buffer);
    return NULL;
  }
  new_buffer[old_length] = c; 
  new_buffer[old_length + 1] = '\0'; 
  return new_buffer;
}

// Usage
buf = append_char(buf, 'a');
over 4 years ago · Santiago Trujillo Denunciar

0

There are a number of problems with your program:

  1. buffer is a local variable of append_char(). As soon as this function returns, the buffer variable becomes unusable. You need to pass in the address of buffer to write the address returned by malloc() and realloc() to buffer.
  2. buf is a pointer to a char. sizeof (buf) does not depend on the number of characters in buf.
  3. You do not check the return value from realloc().
  4. You are not allocating space for the NUL terminator.
  5. You do not call free() after you are done.

Here is one way to achieve what you are trying to do (although I am not trying to fix all the problems I mentioned above):

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

void append_char(char **buffer, char c) {
        if(*buffer == NULL) {
                if((*buffer = malloc(sizeof(char) + 1)) == NULL) { /* + 1 for the NUL terminator */
                        fprintf(stderr, "COuld not allcocate memory to buffer\n");
                        return;
                }
                (*buffer)[0] = (*buffer)[1] = '\0';
        } else {
                *buffer = realloc(*buffer, strlen(*buffer) + sizeof(char) + 1 /* for the NUL terminator */);
        }
        (*buffer)[strlen(*buffer) + 1] = '\0';
        (*buffer)[strlen(*buffer)] = c;       
}

int main(void)
{
        char *buf = NULL;
        append_char(&buf, 'a');
        append_char(&buf, '\0');
        printf("buffer: %s\n", buf);
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda