Skip to content

Instantly share code, notes, and snippets.

@taq
Created October 21, 2026 21:58
Show Gist options
  • Select an option

  • Save taq/81e27c74817c3a1b73fb8a9a79304691 to your computer and use it in GitHub Desktop.

Select an option

Save taq/81e27c74817c3a1b73fb8a9a79304691 to your computer and use it in GitHub Desktop.
A longjmp problem example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <setjmp.h>
jmp_buf env;
char *buffer = NULL;
void funcao_que_aloca(void) {
buffer = malloc(64);
printf("Alocou buffer em %p\n", (void *)buffer);
strcpy(buffer, "dados importantes");
// Simula um erro no meio do caminho
printf("Erro! Indo embora com longjmp...\n");
longjmp(env, 1); // pula direto, sem free()
// Esse código nunca roda
printf("Isso nunca aparece\n");
free(buffer);
}
int main(void) {
if (setjmp(env) == 0) {
printf("Chamando funcao_que_aloca...\n");
funcao_que_aloca();
} else {
printf("Voltei pelo longjmp!\n");
if (buffer) {
printf("Buffer ainda existe: %s (vazamento)\n", buffer);
// Em código real você não sabe se pode liberar ou não
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment