Erik Fredericks, frederer@gvsu.edu Fall 2025
Based on material provided by Erin Carrier, Austin Ferguson, and Katherine Bowers
#include <string.h>
Zero-ing out memory:
int* data = (int*)malloc(sizeof(int) * 32); for(int i = 0; i < 32; i++){ data[i] = 0 }
Alternative:
memset(void* s, int c, size_t n);
n
s
c
Does this work?
memset(data, 1, 32 * sizeof(int));
int* data = (int*)malloc(sizeof(int) * 32); int* copy = (int*)malloc(sizeof(int) * 32); for(int i = 0; i < 32; i++){ copy[i] = data[i]; }
memcpy(void* dest, void* src, size_t n);
Copy n bytes: memcpy(copy, data, 32 * sizeof(int));
memcpy(copy, data, 32 * sizeof(int));
memmove(void* dest, void* src, size_t n);
Copy n bytes, allowing for overlapping buffers:
memmove(copy, data, 32 * sizeof(int));
How are they different?
\0
String functions we'd like to have?
strcat(char *s1, char* s2);
Appends copy of s2 to s1
s2
s1
strncat(char* s1, char* s2, size_t n);
Can also use string formatting
sprintf(char *s1, char* format_str, ...);
Same idea and formatting as printf
printf
Stores result in s1, adds terminator
Returns new length of s1
sprintf(s, "x = %d", 5);
strcpy(char* dest, char* src);
src
dest
\0'
strncpy(char* dest, char* src, size_t n);
'\0'
strlen(char* s);
int strcmp(char* s1, char* s2);
if s1 < s2
if s1 > s2
int strncmp(char* s1, char* s2, size_t n);
char* strchr(char *s, int c);
NULL
char* strrchr(char *s, int c);
char* strstr(char* s1, char* s2);
nope! initializes with a byte, not an int memset(data, 'a', 32) -- change int to char
overlapping memory regions - undefined behavior eg copying a string to itself...