Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de C
C
Getting StartedSyntax BasicsTypes and DataModules and LibrariesErrors and TestingKey Concepts: Pointers and Memory
Debates

Guía de C · 6/6

Key Concepts: Pointers and Memory

Por ahora, este capítulo solo está disponible en inglés.

Pointers and manual memory management define C, and cause most of its bugs. Once pointers click, arrays, strings, and dynamic structures turn out to be one idea.

Addresses and pointers

Every object lives at some address. &x yields the address of x, a pointer stores it, and *p (dereferencing) reads or writes the object it points to.

#include <stdio.h>

void swap(int *a, int *b) {   /* modifies the caller's variables */
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 10, y = 20;
    int *p = &x;          /* p holds the address of x */

    printf("address of x: %p\n", (void *)p);
    *p = 15;              /* x is now 15 */
    swap(&x, &y);
    printf("x=%d y=%d\n", x, y);   /* x=20 y=15 */

    return 0;
}

Arguments are still passed by value, but a copied address still reaches the caller's object. Use NULL for pointers with no target and check before dereferencing.

Pointer arithmetic and arrays

Pointer arithmetic counts elements, not bytes: for an int *p, p + 1 is the next int. An array name usually converts to a pointer to its first element, so a[i] is *(a + i).

#include <stdio.h>

int sum(const int *begin, const int *end) {
    int total = 0;
    for (const int *p = begin; p != end; p++) {
        total += *p;
    }
    return total;
}

int main(void) {
    int a[] = {1, 2, 3, 4, 5};
    size_t n = sizeof a / sizeof a[0];

    int *p = a;                         /* same as &a[0] */
    printf("%d %d\n", *(p + 2), a[2]);  /* 3 3 */

    printf("%d\n", sum(a, a + n));      /* a + n: one past the end */
    return 0;
}

A pointer may point into an array or one past its end, but that last position is for comparisons only. Subtracting two pointers gives a ptrdiff_t element count, and only within the same array.

malloc and free

Data sized at run time, or that outlives its function, goes on the heap (<stdlib.h>):

  • malloc(size) allocates size bytes with indeterminate contents.
  • calloc(count, size) allocates and zero-fills.
  • realloc(ptr, size) resizes, possibly moving the block to a new address.
  • free(ptr) releases the block; free(NULL) is a no-op.
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t cap = 4, len = 0;
    int *items = malloc(cap * sizeof *items);
    if (items == NULL) return 1;        /* allocation can fail */

    for (int v = 1; v <= 10; v++) {
        if (len == cap) {
            size_t new_cap = cap * 2;
            int *tmp = realloc(items, new_cap * sizeof *tmp);
            if (tmp == NULL) {          /* items is still valid */
                free(items);
                return 1;
            }
            items = tmp;
            cap = new_cap;
        }
        items[len++] = v * v;
    }
    printf("len=%zu cap=%zu last=%d\n", len, cap, items[len - 1]);

    free(items);
    items = NULL;                       /* guard against reuse */
    return 0;
}
¿Tienes preguntas sobre este capítulo?
Capítulo anteriorErrors and Testing

Assigning realloc straight back to the original pointer leaks the block on failure, hence the temporary. sizeof *items stays right if the element type changes.

Ownership conventions

Nothing frees memory for you, so every allocation needs a clear owner:

  • Pair every xxx_create that allocates with an xxx_destroy.
  • A const T * parameter is borrowed: the function neither frees nor keeps it.
  • Each block has exactly one owner that releases it.
#include <stdlib.h>
#include <string.h>

typedef struct {
    char *name;      /* owned; freed in player_destroy */
    int score;
} Player;

/* Returns a new Player or NULL. Caller releases it with player_destroy. */
Player *player_create(const char *name, int score) {
    Player *p = malloc(sizeof *p);
    if (p == NULL) return NULL;
    p->name = malloc(strlen(name) + 1);
    if (p->name == NULL) {
        free(p);
        return NULL;
    }
    strcpy(p->name, name);       /* safe: buffer sized exactly */
    p->score = score;
    return p;
}

void player_destroy(Player *p) {
    if (p == NULL) return;
    free(p->name);
    free(p);
}

Undefined behavior to avoid

Undefined behavior (UB) means the standard places no requirements on the result: code can work today and break under another compiler or optimization level.

MistakeExamplePrevention
Null dereference*p with p == NULLCheck before dereferencing
Out-of-bounds accessa[n]Pass lengths and check them
Use after freefree(p); p->xSet pointers to NULL after freeing
Double freefree(p); free(p);Give each block one owner
Uninitialized readint x; x + 1Initialize at declaration
Returning a local's addressreturn &local;Allocate or use a caller buffer
Signed overflowINT_MAX + 1Check ranges before the operation
Modifying a string literalchar *s = "hi"; s[0] = 'H';Use char s[] = "hi";

Warnings, sanitizers, and tools like Valgrind catch most of these during development.

Summary

  • Pointers hold addresses: & takes one, * dereferences. Check for NULL first.
  • Pointer arithmetic is valid only within an array or one past its end.
  • Check every malloc, route realloc through a temporary, and free each block exactly once.
  • Make ownership explicit with create/destroy pairs.
  • Find undefined behavior with tools; prevent it with discipline.

Further reading

  • cppreference: C reference, language and library
  • GCC online documentation, compiler options and warnings
  • Clang AddressSanitizer
  • Clang UndefinedBehaviorSanitizer
  • SEI CERT C Coding Standard, rules for secure C
  • ISO/IEC JTC1/SC22/WG14, the C committee and standard drafts

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.