Communitygithub.com

JantonioFC/skillsbank

Guías de código super-específicas para el lenguaje C.

¿Qué es skillsbank?

Este skill proporciona un conjunto de pautas de codificación idiomática y eficiente para el lenguaje C, diseñado para ayudar a desarrolladores y asistentes de IA (como Claude Code, Cursor, Codex, etc.) a escribir código C más seguro, legible y mantenible. Abarca áreas críticas como gestión de memoria, punteros y arrays, manejo de errores, cadenas, estructuras y enumeraciones, preprocesador y anti-patrones comunes. Cada sección incluye ejemplos de código contrapuestos (malas prácticas vs. buenas prácticas) para ilustrar conceptos clave, como evitar fugas de memoria mediante goto cleanup, usar snprintf en lugar de sprintf, y preferir funciones inline sobre macros. El skill está optimizado para identificar y corregir errores típicos en C, como el uso de malloc sin verificar el valor de retorno, comparaciones de punteros en lugar de contenido con strcmp, y la falta de protectores de inclusión en headers. Al integrarse en herramientas de edición asistida por IA, permite generar código C más robusto y alineado con las mejores prácticas del lenguaje.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/JantonioFC/skillsbank/tree/HEAD/skills/c

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

C: Referencia de Eficiencia Idiomática

Tabla de Contenidos

  1. Gestión de Memoria
  2. Punteros y Arrays
  3. Manejo de Errores
  4. Cadenas
  5. Estructuras y Enumeraciones
  6. Preprocesador y Headers
  7. Anti-patrones específicos de C

1. Gestión de Memoria {#memoria}

// ❌ malloc sin verificar el valor de retorno
char *buf = malloc(size);
strcpy(buf, src);

// ✅
char *buf = malloc(size);
if (!buf) return -ENOMEM;
memcpy(buf, src, size);
// ❌ Cast del resultado de malloc (innecesario en C, oculta falta de #include)
int *p = (int *)malloc(n * sizeof(int));

// ✅
int *p = malloc(n * sizeof *p);
// ❌ free sin asignar NULL (riesgo de puntero colgante en ámbito de larga vida)
free(ptr);
// ... código posterior podría usar ptr

// ✅
free(ptr);
ptr = NULL;
// ❌ Olvidar liberar en caminos de retorno temprano
char *a = malloc(100);
char *b = malloc(200);
if (!b) return -1; // fuga de a

// ✅ — etiqueta única de limpieza
char *a = NULL, *b = NULL;
a = malloc(100);
if (!a) goto limpieza;
b = malloc(200);
if (!b) goto limpieza;
// ... usar a, b ...
limpieza:
    free(b);
    free(a);

Usa sizeof *ptr en lugar de sizeof(Tipo) — se mantiene correcto cuando el tipo cambia.


2. Punteros y Arrays {#punteros}

// ❌ Seguimiento manual del tamaño del array
void procesar(int *arr, int len) { ... }
procesar(datos, 10);

// ✅ — pasar tamaño junto al puntero, o usar un struct
typedef struct { int *datos; size_t len; } IntSlice;
// ❌ Aritmética de punteros donde la indexación de arrays es más clara
*(arr + i) = valor;

// ✅
arr[i] = valor;
// ❌ VLA en código de producción (riesgo de desbordamiento de pila, opcional en C11+)
int arr[n];

// ✅
int *arr = malloc(n * sizeof *arr);
if (!arr) return -ENOMEM;
// ... usar arr ...
free(arr);

3. Manejo de Errores {#errores}

// ❌ Usar números mágicos para retornos de error
if (hacer_cosa() == -1) { ... }

// ✅ — definir o usar códigos de error con nombre
#include <errno.h>
if (hacer_cosa() < 0) {
    perror("hacer_cosa");
    return errno;
}
// ❌ Anidamiento profundo de verificaciones de error
int r1 = paso1();
if (r1 == 0) {
    int r2 = paso2();
    if (r2 == 0) {
        int r3 = paso3();
        // ...
    }
}

// ✅ — retorno temprano / goto cleanup
if (paso1() < 0) goto fallo;
if (paso2() < 0) goto fallo;
if (paso3() < 0) goto fallo;
return 0;
fallo:
    limpiar();
    return -1;

goto cleanup es C idiomático para la liberación de recursos — no lo evites por principio.


4. Cadenas {#cadenas}

// ❌ strcpy sin verificar límites
strcpy(dest, src);

// ✅
strncpy(dest, src, sizeof(dest) - 1);
dest[sizeof(dest) - 1] = '\0';
// o mejor: snprintf(dest, sizeof(dest), "%s", src);
// ❌ Uso incorrecto de strcmp
if (str == "hola") { ... } // compara punteros, no contenido

// ✅
if (strcmp(str, "hola") == 0) { ... }
// ❌ Construir cadenas con strcat repetido (O(n²))
char resultado[1024] = "";
for (int i = 0; i < n; i++) {
    strcat(resultado, items[i]);
}

// ✅ — rastrear posición de escritura
char resultado[1024];
int pos = 0;
for (int i = 0; i < n && pos < (int)sizeof(resultado); i++) {
    pos += snprintf(resultado + pos, sizeof(resultado) - pos, "%s", items[i]);
}

Prefiere snprintf sobre sprintf — siempre.


5. Estructuras y Enumeraciones {#estructuras}

// ❌ Struct simple que requiere la palabra clave `struct` en todas partes
struct punto { int x, y; };
struct punto p = {1, 2};

// ✅
typedef struct { int x, y; } Punto;
Punto p = {1, 2};
// ❌ Struct sin inicializar
Punto p;
usar(p.x); // comportamiento indefinido

// ✅
Punto p = {0};
// ❌ Constantes enteras mágicas
if (estado == 3) { ... }

// ✅
typedef enum { ESTADO_INACTIVO, ESTADO_EJECUTANDO, ESTADO_TERMINADO } Estado;
if (estado == ESTADO_TERMINADO) { ... }

6. Preprocesador y Headers {#preprocesador}

// ❌ Macro donde una función inline funciona (sin seguridad de tipos, doble evaluación)
#define MAX(a, b) ((a) > (b) ? (a) : (b))
MAX(x++, y) // x se incrementa dos veces si x > y

// ✅
static inline int max_int(int a, int b) { return a > b ? a : b; }
// ❌ Sin guarda de inclusión
// mi_header.h
struct Foo { int x; };

// ✅
#ifndef MI_HEADER_H
#define MI_HEADER_H
struct Foo { int x; };
#endif
// o: #pragma once (ampliamente soportado, no estándar)

Reserva las macros para compilación condicional y constantes. Usa static inline para lógica.


7. Anti-patrones específicos de C {#antipatrones}

Anti-patrónPreferido
sprintfsnprintf con tamaño de buffer
getsfgets (gets fue eliminado en C11)
Cast del resultado de mallocdejar que la conversión implícita de void* funcione
sizeof(Tipo) en mallocsizeof *ptr
VLA para arrays grandes/de tiempo de ejecuciónasignación en heap
Callbacks void* sin parámetro de contextopasar void *ctx junto al puntero de función
Estado mutable globalpasar estado a través de punteros a struct
assert para manejo de errores en tiempo de ejecucióncódigos de retorno de error adecuados
Falta de const en parámetros de solo lecturaconst char *str
Mezclar signed/unsigned en comparacionesusar tipos consistentes, convertir explícitamente

Limitaciones

  • Estas son pautas específicas del lenguaje y no cubren decisiones arquitectónicas generales.
  • La sobrecompresión podría reducir la legibilidad; aplica tu criterio.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

JantonioFC/skillsbank

AI-powered image editing with style transfer and object removal

JantonioFC/skillsbank

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

JantonioFC/skillsbank

Analise e auditoria de editais de leilao judicial e extrajudicial. Riscos ocultos, clausulas perigosas, debitos, ocupante e classificacao da oportunidade.

JantonioFC/skillsbank

Embed Photopea in web apps using photopea.js. Covers embedding, file I/O, scripting, exporting, layers, text, filters, and the full Photoshop-compatible API.

JantonioFC/skillsbank

Best practices for Remotion - Video creation in React

JantonioFC/skillsbank

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

JantonioFC/skillsbank

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

JantonioFC/skillsbank

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

JantonioFC/skillsbank

Video and audio perception, indexing, and editing. Ingest files/URLs/live streams, build visual/spoken indexes, search with timestamps, edit timelines, add overlays/subtitles, generate media, and create real-time alerts.

JantonioFC/skillsbank

Upload, stream, search, edit, transcribe, and generate AI video and audio using the VideoDB SDK.

JantonioFC/skillsbank

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

JantonioFC/skillsbank

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

JantonioFC/skillsbank

Tool lifecycle UI components for React/Next.js from ui.inference.sh. Display tool calls: pending, progress, approval required, results. Capabilities: tool status, progress indicators, approval flows, results display. Use for: showing agent tool calls, human-in-the-loop approvals, tool output. Triggers: tool ui, tool calls, tool status, tool approval, tool results, agent tools, mcp tools ui, function calling ui, tool lifecycle, tool pending

JantonioFC/skillsbank

Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

JantonioFC/skillsbank

When the user wants help with paid advertising campaigns on Google Ads, Meta (Facebook/Instagram), LinkedIn, Twitter/X, or other ad platforms. Also use when the user mentions 'PPC,' 'paid media,' 'ROAS,' 'CPA,' 'ad campaign,' 'retargeting,' 'audience targeting,' 'Google Ads,' 'Facebook ads,'...

JantonioFC/skillsbank

Create AI avatar and talking head videos with OmniHuman, Fabric, PixVerse via inference.sh CLI. Models: OmniHuman 1.5, OmniHuman 1.0, Fabric 1.0, PixVerse Lipsync. Capabilities: audio-driven avatars, lipsync videos, talking head generation, virtual presenters. Use for: AI presenters, expla...

JantonioFC/skillsbank

Create AI marketing videos for ads, promos, product launches, and brand content. Models: Veo, Seedance, Wan, FLUX for visuals, Kokoro for voiceover. Types: product demos, testimonials, explainers, social ads, brand videos. Use for: Facebook ads, YouTube ads, product launches, brand awarene...

JantonioFC/skillsbank

Generate AI videos with Google Veo, Seedance, Wan, Grok and 40+ models via inference.sh CLI. Models: Veo 3.1, Veo 3, Seedance 1.5 Pro, Wan 2.5, Grok Imagine Video, OmniHuman, Fabric, HunyuanVideo. Capabilities: text-to-video, image-to-video, lipsync, avatar animation, video upscaling, fole...

JantonioFC/skillsbank

Production-ready CI/CD configurations for Playwright — GitHub Actions, GitLab CI, CircleCI, Azure DevOps, Jenkins, Docker, parallel sharding, reporting, code coverage, and global setup/teardown.

JantonioFC/skillsbank

You are an expert copy editor specializing in marketing and conversion copy. Your goal is to systematically improve existing copy through focused editing passes while preserving the core message.

Skills relacionados