Created
July 8, 2012 16:52
-
-
Save hraban/3071749 to your computer and use it in GitHub Desktop.
Example of a function that does not like overlapping buffers
This file contains 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 <assert.h> | |
#include <ctype.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#define BUF_SIZE 256 | |
/* source and destination buffers MUST NOT overlap */ | |
char * | |
prune_spaces(char * dst, size_t dst_len, const char * src) | |
{ | |
char * const original_destination = dst; | |
assert(src != NULL); | |
assert(dst != NULL); | |
assert(dst_len > 0); | |
for (;;) { | |
if (dst_len == 1 || *src == '\0') { | |
*dst = '\0'; | |
break; | |
} | |
if (!isspace(*src)) { | |
*dst = *src; | |
dst++; | |
dst_len--; | |
} | |
src++; | |
} | |
return original_destination; | |
} | |
int | |
main(int argc, char *argv[]) | |
{ | |
(void) argc; | |
(void) argv; | |
char read_buf[BUF_SIZE]; | |
char prune_buf[BUF_SIZE]; | |
for (;;) { | |
printf("> "); | |
fflush(stdout); | |
fgets(read_buf, BUF_SIZE, stdin); | |
printf("%s\n", prune_spaces(prune_buf, BUF_SIZE, read_buf)); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment