problem with free()

This is a discussion on problem with free() within the C Programming forums, part of the General Programming Boards category; Could anyone explain to me what I am doing wrong here please? Code: void testFree(){ char * s=(char *)calloc(sizeof(char),5); sprintf(s, ...

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    39

    problem with free()

    Could anyone explain to me what I am doing wrong here please?
    Code:
    void testFree(){
    	char * s=(char *)calloc(sizeof(char),5);
    	sprintf(s, "[%d]",321);
    	printf(s);
    	free(s);
    	return;
    }
    I get this error:
    Name:  2150ody.png
Views: 52
Size:  13.6 KB

  2. #2
    Registered User
    Join Date
    Sep 2011
    Location
    Stockholm, Sweden
    Posts
    131
    The string you are writing to s contains 6 elements (remember the terminating null character), but you only allocated memory for 5.

  3. #3
    Registered User
    Join Date
    Dec 2009
    Posts
    39
    ok, I thought I'd forgotten someting having to do with EOS. Thx!

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,855
    > printf(s);
    Also, get into the habit of ALWAYS specifying a const format string for printf, even if it is just "%s".

    If s were user input, any % characters would cause all sorts of havoc.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. i have a problem with free();
    By nik2 in forum C Programming
    Replies: 12
    Last Post: 03-07-2010, 02:09 AM
  2. Problem with Free.
    By chakra in forum C Programming
    Replies: 9
    Last Post: 12-15-2008, 11:20 AM
  3. free() problem
    By audinue in forum C Programming
    Replies: 19
    Last Post: 07-20-2008, 12:18 AM
  4. buy one get one free problem
    By Nick_365 in forum C++ Programming
    Replies: 29
    Last Post: 02-12-2006, 02:17 AM
  5. free problem with struct
    By Massive in forum C Programming
    Replies: 8
    Last Post: 07-29-2003, 07:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21