Skip to content

Instantly share code, notes, and snippets.

@hraban
Created July 8, 2012 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hraban/3071749 to your computer and use it in GitHub Desktop.
Save hraban/3071749 to your computer and use it in GitHub Desktop.
Example of a function that does not like overlapping buffers
#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