Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8185547
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T01:53:08+00:00 2026-06-07T01:53:08+00:00

I have a fairly simple program, I write to a string with snprintf, if

  • 0

I have a fairly simple program, I write to a string with snprintf, if I need to, I extend the string length to accomodate for what I’m trying to write to it. Then, I try to add to that string. It does work, but when I free the malloc’d variable, it crashes.

The code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int ac, char **av) {
    char buf[16];
    char *str = buf;
    char *extra = NULL;
    int len;

    if(!av[1]) {
        return 0;
    }

    if((len = snprintf(str, 16, "%s", av[1])) >= 16) {
        printf("more than 15 chars, %d\n",len);
        if (extra = malloc((len + 1) * sizeof(char))) {
            snprintf(str = extra, len + 1, "%s", av[1]);
        }
    } else {
        printf("less than 15 chars, %d\n",len);
    }

    printf("%s\n", str);


    if((len = snprintf(str+strlen(str), 16, "%s", av[1])) >= 16) {
        printf("more than 15 chars, %d, required: %d\n",len,(len + strlen(av[1]) + 1));
        if ((extra = malloc((len + strlen(av[1]) + 1) * sizeof(char)) ) && strcpy(extra,str)) {
            str = extra;
            snprintf(extra+strlen(av[1]), len + 1, "%s", av[1]);
        }
    } else {
        printf("less than 15 chars, %d\n",len);
    }
    printf("%s\n", str);

    if(extra) {
        free(extra);
    }

    return 1;
}

the output:

more than 15 chars, 16
1234567890123456
more than 15 chars, 16, required: 33
12345678901234561234567890123456
*** glibc detected *** ./testprog: free(): invalid next size (fast): 0x0000000000ce0030 ***
======= Backtrace: =========
/lib/libc.so.6(+0x78a56)[0x7fe46c0b9a56]
./testprog[0x4008c7]
/lib/libc.so.6(__libc_start_main+0xf5)[0x7fe46c062455]
./testprog[0x4005a9]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:03 26355255                           /home/joachim/kc/testprog
00600000-00601000 rw-p 00000000 08:03 26355255                           /home/joachim/kc/testprog
00ce0000-00d01000 rw-p 00000000 00:00 0                                  [heap]
7fe46be2c000-7fe46be41000 r-xp 00000000 08:03 15077980                   /usr/lib/libgcc_s.so.1
7fe46be41000-7fe46c040000 ---p 00015000 08:03 15077980                   /usr/lib/libgcc_s.so.1
7fe46c040000-7fe46c041000 rw-p 00014000 08:03 15077980                   /usr/lib/libgcc_s.so.1
7fe46c041000-7fe46c1d8000 r-xp 00000000 08:03 393241                     /lib/libc-2.15.so
7fe46c1d8000-7fe46c3d8000 ---p 00197000 08:03 393241                     /lib/libc-2.15.so
7fe46c3d8000-7fe46c3dc000 r--p 00197000 08:03 393241                     /lib/libc-2.15.so
7fe46c3dc000-7fe46c3de000 rw-p 0019b000 08:03 393241                     /lib/libc-2.15.so
7fe46c3de000-7fe46c3e2000 rw-p 00000000 00:00 0 
7fe46c3e2000-7fe46c403000 r-xp 00000000 08:03 393253                     /lib/ld-2.15.so
7fe46c5d5000-7fe46c5d8000 rw-p 00000000 00:00 0 
7fe46c600000-7fe46c603000 rw-p 00000000 00:00 0 
7fe46c603000-7fe46c604000 r--p 00021000 08:03 393253                     /lib/ld-2.15.so
7fe46c604000-7fe46c605000 rw-p 00022000 08:03 393253                     /lib/ld-2.15.so
7fe46c605000-7fe46c606000 rw-p 00000000 00:00 0 
7fff72b84000-7fff72ba5000 rw-p 00000000 00:00 0                          [stack]
7fff72bff000-7fff72c00000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
Aborted

Now I’m not exactly what you would call a C-expert so the mistake is probably fairly simple, but I’ve not been able to fix this myself/find anything useful online.

Thanks for the help!

edit:

the fixed code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int ac, char **av) {
    char buf[16];
    char *str = buf;
    char *extra = NULL;
    int len;
    int ssize = 16;
    if(ac != 2)
    {
        return 0;
    }


    if((len = snprintf(str, 16, "%s", av[1])) >= 16) {
        printf("more than 15 chars, %d\n",len);
        if (extra = malloc((len + 1) * sizeof(char))) {
        ssize = (len + 1);
          snprintf(str = extra, len + 1, "%s", av[1]);
        } 
    } else {
        printf("less than 15 chars, %d\n",len);
    }

    printf("%s\n", str);

    char *extra2 = NULL;
    printf("space: %d (%d-%d)\n",ssize-strlen(str),ssize,strlen(str));
    if((len = snprintf(str+strlen(str), ssize-strlen(str), "%s", av[1])) >= ssize-strlen(str)) {
        printf("more than 15 chars, %d, required: %d (strlen: %d)\n",len,(len + strlen(av[1]) + 1),strlen(str));


        if ((extra2 = malloc((len + strlen(av[1]) + 1) * sizeof(char)) ) && strcpy(extra2,str)) {
          str = extra2;
        ssize = (len + strlen(av[1]) + 1);
          snprintf(extra2+strlen(av[1]), len + 1, "%s", av[1]);
        } else printf("failed extraing");
    } else {
        printf("less than 15 chars, %d\n",len);
    }
    printf("%s\n", str);

    if(extra) {
        free(extra);
    }
    if(extra2) {
        free(extra2);
    }

    return 1;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T01:53:10+00:00Added an answer on June 7, 2026 at 1:53 am

    In the second copy to the string you use this code, which tells snprintf() that there are 16 bytes in the buffer:

    if((len = snprintf(str+strlen(str), 16, "%s", av[1])) >= 16) {
    

    But you have passed str + strlen(str) as the address to write to. Obviously you don’t have 16 bytes available from this address, you only have 1 (assuming you initially entered a string longer than 16 and you then allocated len + 1 bytes). So when you tell snprintf() there are 16 it writes past the end of the memory you have allocated, which can sometimes only show up as a problem when you try to free it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We have a fairly simple program that's used for creating backups. I'm attempting to
I have a very simple program that I am trying to improve performance. One
I have a fairly simple program based largely on a simple bluetooth test client
I'm trying to write a simple program to monitor a folder for new files
I have a fairly simple question that has me stymied. I am trying to
I have a fairly simple web2py form with a few validators like, IS_FLOAT_IN_RANGE(...) on
I have a fairly simple question, however the answer seems to elude me. If
I have a fairly simple query: SELECT invoice_id WHERE employee_id = 'XXXX' AND customer_id
I have a fairly simple block of code. Sub Run(Name) on error resume next
I have a fairly simple python loop that calls a few functions, and writes

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.