Skip to content

Instantly share code, notes, and snippets.

@sgharms
Created January 10, 2013 20:10
Show Gist options
  • Save sgharms/4505372 to your computer and use it in GitHub Desktop.
Save sgharms/4505372 to your computer and use it in GitHub Desktop.
Demonstrating some of the interesting challenges in C programming. To clarify these concepts I referred to: http://www.geeksforgeeks.org/memory-layout-of-c-program/.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void printer(char *aString);
void printerX(char *aString);
int main(int argc, char *argv[]){
char *simpleString = "Hello, World";
printer(simpleString);
return 0;
}
void printer(char *aString){
printf("%s was passed in.\n", aString);
printf("'%c' was at element 2\n", aString[2]);
printf("'%c' was at element 10\n", *(aString + 10));
/* This will not work and will cause a segfault */
aString[2] = 'X';
}
void printerX(char *aString){
int len = strlen(aString);
char copy[len];
strcpy(copy, aString);
printf("saw a length of %i for clone '%s'\n", len, copy);
copy[2] = 'X';
*( copy + 3 ) = 'Y';
printf("saw a length of %i for clone '%s'\n", len, copy);
}
// Running `printer` function in main
➜ ex1 git:(master) ✗ ./teststr
Hello, World was passed in.
'l' was at element 2
'l' was at element 10
[1] 29283 segmentation fault ./teststr
Moving the initial string: simpleString to outside of main did not change things.
Hello, World was passed in.
'l' was at element 2
'l' was at element 10
[1] 29336 segmentation fault ./teststr
Valgrind reports:
==29347== Memcheck, a memory error detector
==29347== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==29347== Using Valgrind-3.6.1-Debian and LibVEX; rerun with -h for copyright info
==29347== Command: ./teststr
==29347==
Hello, World was passed in.
'l' was at element 2
'l' was at element 10
==29347==
==29347== Process terminating with default action of signal 11 (SIGSEGV)
==29347== Bad permissions for mapped region at address 0x8048632
==29347== at 0x804848B: printer (teststr.c:22)
==29347== by 0x8048429: main (teststr.c:11)
==29347==
==29347== HEAP SUMMARY:
==29347== in use at exit: 0 bytes in 0 blocks
==29347== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==29347==
==29347== All heap blocks were freed -- no leaks are possible
==29347==
==29347== For counts of detected and suppressed errors, rerun with: -v
==29347== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 6)
[1] 29347 segmentation fault valgrind ./teststr
saw a length of 12 for clone 'Hello, World'
saw a length of 12 for clone 'HeXYo, World'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment