Created
October 21, 2026 21:58
-
-
Save taq/81e27c74817c3a1b73fb8a9a79304691 to your computer and use it in GitHub Desktop.
A longjmp problem example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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